1.传递多个参数的方法
如下面代码所示
def test(*paramter)
for i in 0...paramter.length
puts "test中的第#{i}个参数为:#{paramter[i]}"
end
end
test(1,3,6,"你好","我不好",3.14)
2.迭代器
ruby中有两个迭代器,each和collect
each常用来执行一段代码
a = [1,2,3,4,5]
a.each do |x|
puts x*10
end
collect用来返回处理后的结果
a = [1,2,3,4,5]
b = a.collect{ |x|x*10 }
#执行后b的值为[10, 20, 30, 40, 50]
数组
2.4.0 :052 > a=(0..9).to_a #range转数组
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.4.0 :053 > a.push(10) #往数组里添加元素
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2.4.0 :054 > a<<11 #相当于a.push(11)
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
2.4.0 :055 > a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
2.4.0 :056 > a<<"hello" #相当于a.push("hello")
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "hello"]
2.4.0 :057 > a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "hello"]
2.4.0 :058 > a<<"world"<<"tttt"
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "hello", "world", "tttt"]
2.4.0 :059 > a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "hello", "world", "tttt"]
2.4.0 :060 > b=(20..22).to_a
=> [20, 21, 22]
2.4.0 :061 > a<<b #往数组里添加数组元素
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "hello", "world", "tttt", [20, 21, 22]]
2.4.0 :062 > a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "hello", "world", "tttt", [20, 21, 22]]
ruby专属的骚操作
2.4.0 :068 > a=(0..9).to_a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.4.0 :069 > a[2..(a.length-1)] #从a[2]到数组结尾
=> [2, 3, 4, 5, 6, 7, 8, 9]
%w用于创建元素为字符串的数组
2.4.0 :070 > %w[a b d]
=> ["a", "b", "d"]
不为人知的数据类型
1.符号类型(Symbol )
1.1一般不给一个变量赋 符号类型的值
1.2符号变量常用于哈希(让ruby更加优雅)
2.4.0 :104 > user1={ :name=> "hch",:password=>"159753"} #符号类型做哈希的key
=> {:name=>"hch", :password=>"159753"}
2.4.0 :105 > user2={name: "hch2",password: "159753"} #另一种写法,跟上面完全等价
=> {:name=>"hch2", :password=>"159753"}
2.4.0 :106 > user1[:name]
=> "hch"
2.4.0 :107 > user2[:name]
=> "hch2"
嵌套哈希:
2.4.0 :108 > params={} #大括号代表哈希类型,params是一个哈希
=> {}
2.4.0 :109 > params[:user]={name: "hch",password: "159753"} #params[:user]也是一个哈希
=> {:name=>"hch", :password=>"159753"}
2.4.0 :110 > params[:user][:name] #哈希的哈希,嵌套哈希
=> "hch"
1.3符号类型的值,冒号后面必须接字母
还有。。
符号类型嵌入在字符串中时,相当于去掉冒号的字符串
2.4.0 :005 > s=:test
=> :test
2.4.0 :006 > "#{s}测试"
=> "test测试"
2.4.0 :007 >
1.4 send方法用于元编程
>> a = [1, 2, 3]
>> a.length
=> 3
>> a.send(:length)
=> 3
>> a.send("length")
=> 3
send方法可以根据传入的字符串/符号类型的参数来动态获取一个类中的属性
2.迭代器(Enumerator)
map.each,collect都是迭代器
2.4.0 :092 > a
=> [3, 4, 5, 6, 7, 8, 9]
2.4.0 :093 > a.map
=> #<Enumerator: [3, 4, 5, 6, 7, 8, 9]:map>
2.4.0 :094 > a.each
=> #<Enumerator: [3, 4, 5, 6, 7, 8, 9]:each>
2.4.0 :095 > a.collect
=> #<Enumerator: [3, 4, 5, 6, 7, 8, 9]:collect>
ruby变量类型
一般小写字母、下划线开头:变量(Variable)。
$开头:全局变量(Global variable)。
@开头:实例变量(Instance variable)。 #java中的private
@@开头:类变量(Class variable)类变量被共享在整个继承链中 #java类中的static
大写字母开头:常数(Constant)。