1

我有以下数组:

arr = [1,2,"car"]

arr.each do |e|
  puts e
end

#=> 1
    2
    car

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

4

3 回答 3

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
于 2013-08-05T03:50:19.010 回答
1
arr = [1,2,"car"]

arr.each_with_index do |e, index|
  puts index, e
end
于 2013-08-05T03:51:44.243 回答
-2

仅获取索引:

arr = [1,2,"car"]
arr.each_index do |index|
  puts index
end
于 2013-08-05T07:18:51.560 回答