Here is my code:
class Array
def anotherMap
self.map {yield}
end
end
print [1,2,3].anotherMap{|x| x}
I'm expecting to get an output of [1,2,3],but I get [nil,nil,nil]
What's wrong with my code?
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
class Array
def another_map(&block)
map(&block)
end
end
Your code doesn't yield the value that's yielded to the block you passed to #map
. You need to supply a block parameter and call yield
with that parameter:
class Array
def anotherMap
self.map {|e| yield e }
end
end
print [1,2,3].anotherMap{|x| x}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With