Ruby:如何从数组中传递元素及其索引?

时间:2013-08-05 03:48:11

标签: ruby

我有以下数组:

arr = [1,2,"car"]

arr.each do |e|
  puts e
end

#=> 1
    2
    car

但是如何制作一个同时显示其索引号的“put e”?

3 个答案:

答案 0 :(得分:3)

arr = [1,2,"car"]

arr.each_with_index() do |e,i|
  puts "#{e} is at index #{i}"
end
# >> 1 is at index 0
# >> 2 is at index 1
# >> car is at index 2

答案 1 :(得分:1)

arr = [1,2,"car"]

arr.each_with_index do |e, index|
  puts index, e
end

答案 2 :(得分:-2)

仅获取索引:

arr = [1,2,"car"]
arr.each_index do |index|
  puts index
end