TomCaps
TomCaps

Reputation: 2527

How to extend array methods in ruby?

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?

Upvotes: 8

Views: 8051

Answers (2)

Phrogz
Phrogz

Reputation: 303215

class Array
  def another_map(&block)
    map(&block)
  end
end

Upvotes: 11

John
John

Reputation: 30185

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}

Upvotes: 9

Related Questions