【问题标题】:Each_with_index method in RubyRuby 中的 each_with_index 方法
【发布时间】:2015-03-29 17:02:04
【问题描述】:

我是 ruby​​ 新手,我现在正在学习循环。我正在使用 each_with_index 方法返回新数组中元素的值和位置。在这里,我创建了一个方法(称为 add_value_and_index),它通过 each_with_index 方法返回新数组(new_array)中的值和位置

def add_value_and_index(array)
  new_array = []
  new_array = array.each_with_index do |element, index|
    p "#{element} is a position #{index}"
  end
  new_array
end

我在 RSPEC 中收到“ExpectationsNotMet”错误,上面的代码中缺少什么才能通过测试?这是它的规格:

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

我得到的错误是:

RSpec::Expectations::ExpectationNotMetError

expected: [2, 2, 2]
     got: [2, 1, 0]

(compared using ==)

exercise_spec.rb:5:in `block (2 levels) in <top (required)>'

【问题讨论】:

  • 如果您添加了失败的测试会有所帮助。
  • 是的,这会有所帮助。你的方法看起来不错,如果“放置”元素和它们的位置是你正在寻找的。​​span>
  • 啊,对不起。这是: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
  • RSpec::Expectations::ExpectationNotMetError expected: [2, 2, 2] got: [2, 1, 0] (compared using ==) exercise_spec.rb:5:in block (2 个级别) in `
  • Sylvee,Cysanfar 没有“看到”它,部分原因是他们可能正在寻找有问题的测试。不要在 cmets 中发布代码更新。我编辑了您的问题以显示 rspec 测试。它应该很快就会出现。将来始终编辑您的问题,而不是在 cmets 中发布代码。

标签: ruby-on-rails ruby rspec


【解决方案1】:

您需要对元素及其索引求和才能通过您的测试:

def add_value_and_index(array)
  new_array = []
  array.each_with_index do |element, index|
    p "#{element} is a position #{index}"
    new_array << element + index
  end
  new_array
end

另一种方法是使用map

def add_value_and_index(array)
  array.map.with_index do |element, index|
    element + index
  end
end

add_value_and_index [2, 1, 0] 
# => [2, 2, 2] 

【讨论】:

  • 这是因为 #each 返回的 self 应该在您的回答中提及。
猜你喜欢
  • 2016-02-23
  • 2011-08-04
  • 2015-05-08
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 2014-10-23
  • 2017-05-28
  • 2012-06-04
相关资源
最近更新 更多