I'm trying to return odd elements using this method
def odd_elements(array)
retArr = Array.new
array.each_with_index do |item, index|
if block_given?
yield(item)
else
retArr << item
end if index % 2 != 0
end
return retArr
end
so that I could pass both these tests
it "should yield odd elements" do
res = odd_elements([1,2,3,4,5,6])
res.should be_an_instance_of Array
res.should have(3).items
res.should include(2)
res.should include(4)
res.should include(6)
end
it "should yield" do
res = odd_elements([1,2,3,4,5,6]) {|x| x**2 }
res.should be_an_instance_of Array
res.should have(3).items
res[0].should == 4
res[1].should == 16
res[2].should == 36
end
but I'm failing in the second one. It seems I don't understand how to yield and I didn't manage to get it right in two hours trying so many different things. Could you please explain me why it does not work?