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

8

这是我的代码:

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

print [1,2,3].anotherMap{|x| x}

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

你在这里想做什么?从当前数组返回一个新的数组吗? - Hunter McMillen
2
顺便说一句,self. 是多余的。 - Marc-André Lafortune
请记得重新启动您的服务器,否则新方法可能还无法使用。 - Kevin Cooper
2个回答

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

9

你的代码没有产生被传递给#map所传递的块的值。你需要提供一个块参数并使用该参数调用yield

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

print [1,2,3].anotherMap{|x| x}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接