gpt4 book ai didi

ruby - 为什么即使在 Hash 上调用 Enumerable#find/#detect 也会返回一个数组?

转载 作者:数据小太阳 更新时间:2023-10-29 06:50:00 24 4
gpt4 key购买 nike

documentation for Enumerable#find/#detect说:

find(ifnone = nil) { |obj| block } → obj or nil
find(ifnone = nil) → an_enumerator

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

但是在Hash上调用时,结果已经将类型改为Array,而不是原来的Hash。

是否存在一些实现错误或关于此数据类型的一些历史约定?

{a: 'a', b:'b'}.find {|k, v| v == 'b'}
# => [:b, 'b']

最佳答案

Hash#detect继承自Enumerable#detect方法。

Enumerable 模块生成多种方法(如sortminmax,包括detect 等)基于包含 Enumerable 的类的 each 方法。

它不关心each是如何实现的,只要它

"...yields successive members of the collection. " from ruby-doc

所以对于Hash#detect方法,它依赖于Hash#each的行为,即:

Calls block once for each key in hsh, passing the key-value pair as parameters. If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200 }
h.each {|key, value| puts "#{key} is #{value}" }

因为 Hash#each 将散列生成为两对数组,所以从 Enumerable 模块继承的所有方法都基于它工作。

这就是为什么 Hash#detect 生成一个包含两个元素的数组而不是哈希对象本身的原因。

关于ruby - 为什么即使在 Hash 上调用 Enumerable#find/#detect 也会返回一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250746/

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