`each_with_index`没有像我想的那样工作

时间:2015-03-07 00:21:47

标签: ruby arrays

我尝试在数组上实现each_with_index方法。

def display_weapons
  puts "Your current list of weapons are: "
  @weapons.each_with_index do |weapon, index|
    puts "#{index + 1}. #{weapon}"
  end
end

我称之为:

@weapons = ["Rockets", "Laser", "Photon blaster", "Plasma cannon"]
puts display_weapons

我得到了结果:

Your current list of weapons are: 
1. Rockets
2. Laser
3. Photon blaster
4. Plasma cannon
Rockets
Laser
Photon blaster
Plasma cannon

我没有得到我想的那样。我只是想问一下这种方法是如何工作的。为什么我要两次获得元素?一次使用索引+ 1,一次不使用。

2 个答案:

答案 0 :(得分:5)

在Ruby中,方法的最后一个语句会自动从它返回。 #each_with_index会返回您迭代的列表,因此您对列表中的每个元素/索引执行puts,然后puts display_weapons调用的结果,即display_weapons武器清单。

只需致电puts display_weapons而不是{{1}}。

答案 1 :(得分:2)

因为您使用返回puts的方法调用了@weapons