迭代器 iterator
- 不同於while迴圈的用法 ,each 是一個陣列的方法,遍歷陣列中的無數,稱之為迭代器iterator
- 其中do….end是each方法的引數 ,稱作匿名方法(code block)
3.times do
puts "hi"
end
code block 匿名函式 (無方法名)
{puts "hello"}
do
puts "Hello"
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
本作品採用《CC 協議》,轉載必須註明作者和本文連結