为什么可枚举#查找/#检测返回叫上一个哈希即使一个数组? [英] Why does Enumerable#find/#detect return an Array even when called on an Hash?
问题描述
为可枚举#查找文档
/ #detect
说:
找到(ifnone =无){| OBJ |块}→OBJ或零
结果找到(ifnone =无)→an_enumerator
在传递的枚举的每个条目的块的。 返回第一个作为该块
是不是假的。如果没有匹配的对象,调用 ifnone 的并返回其
结果,当它被指定,或返回无
其他。
块引用>然而,当它被称为上哈希,结果发生了变化的类型阵列,而不是原来的哈希。
这是一些实现故障或有关此数据类型的一些历史惯例?
{A:'A',B:'B'} {找到| K,V | v =='B'}
#=> [:B,'B']
解决方案的
哈希#检测
是继承可枚举#检测
方法。之类的方法
可枚举
模块产生多种方法(如排序
,分
,最大
包括检测基于
等)每个
,其中包括可枚举
。它并不关心如何
每个
只要是作为它
......产生集合的连续成员。
从红宝石DOC
块引用>因此,对于
哈希#检测
方法,它依赖于哈希#每个
的行为,这就是:
调用阻止一次在HSH每个键,传递键值对的
参数。如果没有块给出,则返回一个枚举器来代替。
块引用>H = {A=> 100,B=> 200}
h.each {|键,值|把#{}键是#{值}由于
每个哈希#
产生的哈希作为两个对数组,从可枚举
模块的作品继承了所有的方法基于这一点。这就是为什么
哈希#检测
产生两个元素的数组,而不是一个哈希对象本身。The documentation for
Enumerable#find
/#detect
says:
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.However, when it is called on the Hash, the result has changed the type to Array instead of the original Hash.
Is it some implementation fault or some historical conventions regarding this datatype?
{a: 'a', b:'b'}.find {|k, v| v == 'b'} # => [:b, 'b']
解决方案The
Hash#detect
is inherited fromEnumerable#detect
method.
Enumerable
module generates multiple methods(such assort
,min
,max
includingdetect
etc.) based on theeach
method of the class which includesEnumerable
.It doesn't care about how
each
is implemented as long as it"...yields successive members of the collection. " from ruby-doc
So for the
Hash#detect
method, it relies onHash#each
's behavior, which is: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}" }
Because
Hash#each
yields the hash as two pair array, all methods inherited from theEnumerable
module works based on that.That's why
Hash#detect
produces a two elements array instead of the an hash object itself.这篇关于为什么可枚举#查找/#检测返回叫上一个哈希即使一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!