迭代常用方法
each
[1, 2, 3, 4, 5].each {|i| puts i}
find
[1,2,3,4,5,6].find {|i| i*i > 30} # 返回6
collect
和map
方法一樣戏蔑,通過block返回一個(gè)新的數(shù)組
["H" , "A" , "L" ].collect {|x| x.succ } # => ["I", "B", "M"]
還有一個(gè)重要的方法是with_index
f = File.open("testfile")
f.each.with_index do |line, index|
puts "Line #{index} is: #{line}"
end
f.close
我們可以是在數(shù)組或hash中使用to_enum
方法蹋凝,轉(zhuǎn)換成功枚舉對象:
a = [ 1, 3, "cat" ]
h = { dog: "canine" , fox: "vulpine" }
# Create Enumerators
enum_a = a.to_enum
enum_h = h.to_enum
enum_a.next # => 1
enum_h.next # => [:dog, "canine"]
enum_a.next # => 3
enum_h.next # => [:fox, "vulpine"]
使用方法loop
來控制枚舉對象
short_enum = [1, 2, 3].to_enum
long_enum = ('a' ..'z' ).to_enum
loop do
puts "#{short_enum.next} - #{long_enum.next}"
end
produces:
1 - a
2 - b
3 - c
對數(shù)組或字符串的其他常用迭代方法:
result = []
[ 'a' , 'b' , 'c' ].each_with_index {|item, index| result << [item, index] }
result # => [["a", 0], ["b", 1], ["c", 2]]
result = []
"cat".each_char.each_with_index {|item, index| result << [item, index] }
result # => [["c", 0], ["a", 1], ["t", 2]]
result = []
"cat".each_char.with_index {|item, index| result << [item, index] }
result # => [["c", 0], ["a", 1], ["t", 2]]
enum = "cat".enum_for(:each_char)
enum.to_a # => ["c", "a", "t"]
enum_in_threes = (1..10).enum_for(:each_slice, 3)
enum_in_threes.to_a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]