在Ruby中,迭代器(Iterator)是一种用于遍历集合元素的机制。迭代器提供了一种简单而统一的方式来处理数组、哈希、范围等集合类型。以下是一些关于Ruby迭代器的基本操作和示例:

each 迭代器:
# 数组迭代器
arr = [1, 2, 3, 4, 5]
arr.each do |element|
  puts element
end

# 哈希迭代器
hash = { "name" => "John", "age" => 30, "city" => "New York" }
hash.each do |key, value|
  puts "#{key}: #{value}"
end

times 迭代器:
# 使用 times 迭代器
3.times do
  puts "Hello, Ruby!"
end

upto 和 downto 迭代器:
# 使用 upto 迭代器
1.upto(5) do |num|
  puts num
end

# 使用 downto 迭代器
5.downto(1) do |num|
  puts num
end

each_with_index 迭代器:
# 使用 each_with_index 迭代器获取索引
arr = ["apple", "banana", "cherry"]
arr.each_with_index do |fruit, index|
  puts "#{index + 1}. #{fruit}"
end

step 迭代器:
# 使用 step 迭代器
1.step(10, 2) do |num|
  puts num
end

cycle 迭代器:
# 使用 cycle 迭代器循环集合
arr = [1, 2, 3]
arr.cycle(2) do |num|
  puts num
end

map 迭代器:
# 使用 map 迭代器创建新的集合
arr = [1, 2, 3, 4, 5]
squared = arr.map { |num| num * num }
puts squared  # 输出:[1, 4, 9, 16, 25]

这只是Ruby迭代器的一些基本操作。迭代器在Ruby中是非常强大和灵活的工具,用于遍历不同类型的集合。


转载请注明出处:http://www.zyzy.cn/article/detail/6460/Ruby