📜  红宝石 |枚举器 each_with_index函数

📅  最后修改于: 2022-05-13 01:55:12.232000             🧑  作者: Mango

红宝石 |枚举器 each_with_index函数

Ruby 中的 each_with_index函数用于迭代对象及其索引并返回给定对象的值。

示例 1:

# Initialising an array and calling each_with_index function
[5, 10, 15, 20, 25, 30].each_with_index do |num, idx|
      
# Getting the values of the array    
  puts "#{num}"
  if ((idx) % 2 == 0)
    puts "end of line" 
  end 
end 

输出:

5
end of line
10
15
end of line
20
25
end of line
30

示例 2:

# Initialising an array and calling each_with_index function
[5, 10, 15, 20, 25, 30].each_with_index do |num, idx|
      
# Getting the values of the array    
  puts "#{num}"
  if ((idx + 1) % 2 == 0)
    puts "end of line" 
  end 
end 

输出:

5
10
end of line
15
20
end of line
25
30
end of line