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 string puts name <span style="white-space:pre"> </span>#puts -- print out the var sum = 5 + 1.4 puts sum correct = 1 == 1 puts 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}!" end clock("10:00pm") #note the ""
7. if ... else ... end
num = 6 if 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" end end person1 = Person.new person1.hello person2 = Person.new person2.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" end end person1 = Person.new("Lupe", 8) person1.intro class Dog def initialize(name,color) @name = name @color= color end def describe puts "My name is #{@name} and I am #{@color}" end end dog1 = Dog.new("Rover","beige") dog1.describe