gpt4 book ai didi

ruby - 如何向 Enumerable 模块添加方法?

转载 作者:太空宇宙 更新时间:2023-11-03 17:33:01 26 4
gpt4 key购买 nike

如何将自定义方法添加到 Ruby 中现有的 Enumerable 模块?我正在运行 Ruby 2.0。

最佳答案

与您向每个其他模块添加方法的方式相同。

如果你想添加带有参数bazquux的方法bar到你写的模块Foo

module Foo
def bar(baz, quux)
# code code code
end
end

因此,如果您想将方法histogram 添加到模块Enumerable 中,您可以编写

module Enumerable
# Counts the number of occurrences of each unique object in `self`.
#
# @return [Hash<E, Integer>] a `Hash` of objects mapped to number of occurrences in `self`.
def histogram
group_by(&:itself).map {|k, v| [k, v.size] }.to_hash
end
end

关于ruby - 如何向 Enumerable 模块添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27735110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com