【问题标题】:using each_with_index and adding values with corresponding index for a new array [closed]使用 each_with_index 并为新数组添加具有相应索引的值[关闭]
【发布时间】: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


【解决方案1】:

您可以使用map来准确返回结果:

def add_value_and_index(array)
  array.map.with_index { |value, index| value + index }
end

如果课程尚未使用map,您可以创建一个新数组并将总和添加到每次迭代中:

def add_value_and_index(array)
  result = []
  array.each_with_index { |value, index| result << value + index }
  result
end

我不会在生产中使用第二个示例,因为它冗长且难以阅读。

【讨论】:

  • 如果我被限制使用 .map 怎么办?并且必须使用 each_with_index?
  • 谢谢,非常感谢。这个语法在我的课程中还没有被复习过,但它似乎最符合我的限制。谢谢!
猜你喜欢
  • 2019-07-27
  • 2016-06-22
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 2020-01-07
  • 2014-07-31
相关资源
最近更新 更多