Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend array methods in ruby?

Tags:

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?

like image 760
TomCaps Avatar asked Dec 02 '11 03:12

TomCaps


People also ask

How do you extend an array in Ruby?

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).


2 Answers

class Array
  def another_map(&block)
    map(&block)
  end
end
like image 101
Phrogz Avatar answered Oct 17 '22 07:10

Phrogz


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}
like image 44
John Avatar answered Oct 17 '22 07:10

John