迭代器 iterator
- 不同于while循环的用法 ,each 是一个数组的方法,遍历数组中的无数,称之为迭代器iterator
- 其中do….end是each方法的参数 ,称作匿名方法(code block)
3.times do
puts "hi"
end
code block 匿名函数 (无方法名)
{puts "hello"} # 大括号的匿名函数 单行
do
puts "Hello" # 这也是一段匿名函数 多行用do...end
end
内部迭代器
people = ["Lily" , "Hikari" , "Lucy"]
people.each do |person|
puts person
end
5.times { puts "Ruby"}
1.upto(9){ |x| puts x}
其它迭代方式
a = ["a","b","c","d","e"]
b = a.map do |x|
x + "!"
end
puts b.inspect
b = [1,2,3].find_all do |x|
x % 2 == 0
end
puts b.inspect
a = ["a","b","c"]
a.delete_if do |x|
x >= "b"
end
puts a.inspect
[2,1,3].sort! do |a,b|
b<=>a
end
计算总和 reduce
(5..10).reduce do |sum , n|
sum + n
end
#找出最长字符串
a = ["cat","sheep","bear"]
max = a.reduce do |memo , word|
memo.length > word.length ? memo : word
end
puts max