Create your own # map array as a method

I want to create an instance method of a type Array#my_map, and this method should work with the original method Array#map. I want to get the same result from a new method, as shown below:

arr = [1, 2, 3, 4]
arr.new_map_method do |x|
 x + 1
end # => [2, 3, 4, 5]

arr.new_map_method(&:to_s) # => ["1", "2", "3", "4"]
-2
source share
2 answers

The easiest way to create a method with the same behavior of another method is to use simple alias :

class Array
  alias_method :new_map_method, :map
end

If for some strange reason you do not want to use map, you can use injectinstead:

class Array
  def new_map_method
    return enum_for(__callee__) unless block_given?
    inject([]) {|acc, el| acc << yield(el) }
  end
end
+1
source

Thanks guys! I also made one solution for my qeestion

class Array
 def my_map(&block)
  result = []
  each do |element|
   result << block.call(element)
  end
  result
 end
end

function call

 [1,2,3].my_map(&:to_s)

output => ["1", "2", "3"]

[1, 2, 3, 4, 5].my_map do |x|
  x
end

output => [1, 2, 3, 4, 5]

+1

Source: https://habr.com/ru/post/1655457/


All Articles