Ruby 有4种数据类型:String, Boolen, Array, Hashes
Ruby 有3种操作方法:Method, attribute, ?? Ruby 有xxx: Classes, Object....====先来看数据类型====
1. String and Declaring the variables:
name = "Wonder Woman" #declare a var and store a stringputs name #puts -- print out the varsum = 5 + 1.4puts sumcorrect = 1 == 1puts correct
2. Arrays:
cities = ["chongqing","beijing","shanghai"]puts cities[1]; #print out the SECOND city
3.Hashes:
注意这句话:We can access any value by naming its key
seasons = { "Spring" => 20, "Summer"=>30, "Autumn"=>20, "Winter"=>02}puts seasons["Winter"]#{ ? , ? , ? }# "key"# "key" => value# access: HashName[ "key" ] = value
4. Declare and Refer the variables
foods = ["apple", "pear", "orange"]puts "my favourite foods are #{foods}"# here we use #{} to refer to the variables.
5. Methods
For all object types, Ruby has a number of built in methods that allow us to change the object. Let's look at a few common ones:
a. Strings: .reverse, .capitalize
b. Numbers: + , - , * , /
c. Arrays: .delete, .count
d. Hashes: .compare, .flatten
colors = ["oo", "tt" , "tt", "ff"]puts colors.first # call the method .first on array
6. Define our own methods
def clock(time) puts "It's #{time}!"endclock("10:00pm") #note the ""
7. if ... else ... end
num = 6if num.even? puts "This int is even."else puts "This int is odd."end # don't forget the end
8. Iterator - 迭代器
for Array and Hash ,使用迭代器来遍历Access each element.
names = ["Tommy","Catty","Barry","Sunny"]names.each do |nname| puts "hello #{nname}!"end
9. Classes - 类
关于Class的声明和使用:
class Person def hello puts "hello" endendperson1 = Person.newperson1.helloperson2 = Person.newperson2.hello
another e.g.
class Person def initialize(name, age) @name = name @age = age end def intro puts "My name is #{@name} and I am #{@age} years old" endendperson1 = Person.new("Lupe", 8)person1.introclass Dog def initialize(name,color) @name = name @color= color end def describe puts "My name is #{@name} and I am #{@color}" endenddog1 = Dog.new("Rover","beige")dog1.describe
posted on 2015-04-24 15:59 阅读( ...) 评论( ...)