【发布时间】:2015-04-23 12:31:56
【问题描述】:
这里是红宝石新手。我需要使用 each_with_index 函数来创建一个新数组,将值添加到相应的索引中。下面是我认为的解决方案,但当然,它不起作用。我敢肯定,即使是打印值的 'p' 也是不必要的。
def add_value_and_index(a)
a.each_with_index do |value, index|
p #{value} + #{index}"
end
end
以下是规格:
describe '#add_value_and_index' do
it "returns a new array composed of the value + index of each element in the former" do
expect( add_value_and_index([2,1,0]) ).to eq([2,2,2])
end
end
【问题讨论】:
-
最好使用
map.with_index -
嗯。当前部分课程尚未使用该功能。我目前仅限于这些工具作为循环的介绍
标签: ruby-on-rails ruby arrays loops indexing