迭代器应该返回错误消息Ruby, rspec



我应该从数组返回奇数值,但如果我传递这个

,我一直在rspec中失败
odd_elements([1, 2, 3, 4, 5, 6]) { |x| x**2 }

我的代码是这样的

def odd_elements(array)
    array.values_at(* array.each_index.select {|i| i.odd?})
end

rspec中的代码是:

describe 'Odd iterator' do
 context 'should yield' do
  subject(:res) { odd_elements([1, 2, 3, 4, 5, 6]) { |x| x**2 } }
  it { is_expected.to be_an_instance_of Array }
  it { expect(res.size).to be 3 }
  it { expect(res[0]).to be 4 }
  it { expect(res[1]).to be 16 }
  it { expect(res[2]).to be 36 }
 end
end

我得到的错误是Odd iterator should yield should get 4(另外两个数字,分别是16和36)。

谁能告诉我,为什么花括号里的代码在传递给odd_modules之前没有得到执行?

如果odd_elements由您定义,则由您执行块。

def odd_elements(array)
  array.map! { |item| yield item } if block_given?
  array.select(&:odd?)
end

输出
2.3.1 :088 > odd_elements([1,2,3,4])
 => [1, 3] 
2.3.1 :088 > odd_elements([1,2,3,4]) { |x| x + 1 }
 => [3, 5] 

最新更新