如何在ruby中扩展数组方法?

Tom*_*aps 7 ruby

这是我的代码:

class Array
    def anotherMap
         self.map {yield}
    end
end

print [1,2,3].anotherMap{|x| x}
Run Code Online (Sandbox Code Playgroud)

我期望得到[1,2,3]的输出,但我得到[nil,nil,nil]
我的代码出了什么问题?

Joh*_*ohn 9

您的代码不会产生您传递给的块所产生的值#map.您需要提供一个块参数并yield使用该参数调用:

class Array
    def anotherMap
         self.map {|e| yield e }
    end
end

print [1,2,3].anotherMap{|x| x}
Run Code Online (Sandbox Code Playgroud)


Phr*_*ogz 9

class Array
  def another_map(&block)
    map(&block)
  end
end
Run Code Online (Sandbox Code Playgroud)