迭代常用方法
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返回一个新的数组
["H" , "A" , "L" ].collect {|x| x.succ } # => ["I", "B", "M"]
还有一个重要的方法是with_index
f = File.open("testfile")
f.each.with_index do |line, index|
puts "Line #{index} is: #{line}"
end
f.close
我们可以是在数组或hash中使用to_enum
方法,转换成功枚举对象:
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
对数组或字符串的其他常用迭代方法:
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]]