methods - Return a new array modified from a block/yield in ruby -
i have started full-stack developer course @ bloc.io, , struggling on assignment. cannot seem find issue code, bit unclear assignment may asking for. guidance appreciated. assignment gives following examples. apologize length of post, wanted thorough possible.
def return_bigger(array) array.map |item| yield(item) end end return_bigger([1,2,3,4]) |item| item + 1000 end #=> [1001, 1002, 1003, 1004] return_bigger(["cat", "hat", "bat"]) |item| item.capitalize end #=> ["cat", "hat", "bat"]
new_each([1,2,3,4]) |item| p "whatever want! item: #{item}" end
def new_each(array) 0.upto(array.length - 1) |index| yield( array[index] ) end end
then describes assignment follows:
define new_map function. should take array argument , return new array modified according instructions passed in block. feel free use each within method, rather array indexing used above.
the first step in re-implementing map should iterate on array:
def new_map(array) array.each |item| end end
the new_map method quite similar our new_each method, rather performing "side effect" behavior each element, you'll want store return value each block invocation in new array:
def new_map(array) new_array = [] array.each |item| # invoke block, , add return value new array end end
when you've finished iterating through old array, return new 1 new_map function.
from can comprehend, assignment wants me replicate new_each method without use of .map store in "new_array" however, unsure flaw in code is. there reason code not "yielding" blocks have defined? code have come with:
def new_map(array) new_array = [] array.each |item| yield(item) new_array << item end end new_map([1,2,3,4]) |item| item + 1 end new_map(["cat", "hat", "bat"]) |item| item.capitalize end
assignment:
new_map should not call map or map! rspec::expectations::expectationnotmeterror expected: [2, 3, 4] got: [1, 2, 3] (compared using ==) exercise_spec.rb:9:in `block (2 levels) in <top (required)>' new_map should map object rspec::expectations::expectationnotmeterror expected: [fixnum, string, symbol] got: [1, "two", :three] (compared using ==) exercise_spec.rb:14:in `block (2 levels) in <top (required)>'
specs:
describe "new_map" "should not call map or map!" = [1, 2, 3] a.stub(:map) { '' } a.stub(:map!) { '' } expect( new_map(a) { |i| + 1 } ).to eq([2, 3, 4]) end "should map object" = [1, "two", :three] expect( new_map(a) { |i| i.class } ).to eq([fixnum, string, symbol]) end end
two tiny mistakes: fact stuffing new_array
original items, rather transformed items getting yield item
, , (as mentioned cary swoveland in comments) not returning new_array
. is, returning last computed value, result of array.each
, array
- instead of computed result, returning original array. why receiving [1, 2, 3]
when expecting [1+1, 2+1, 3+1]
.
Comments
Post a Comment