为什么可枚举#查找/#检测返回叫上一个哈希即使一个数组? [英] Why does Enumerable#find/#detect return an Array even when called on an Hash?

查看:184
本文介绍了为什么可枚举#查找/#检测返回叫上一个哈希即使一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可枚举#查找文档 / #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 from Enumerable#detect method.

Enumerable module generates multiple methods(such as sort, min, max including detect etc.) based on the each method of the class which includes Enumerable.

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 on Hash#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 the Enumerable module works based on that.

That's why Hash#detect produces a two elements array instead of the an hash object itself.

这篇关于为什么可枚举#查找/#检测返回叫上一个哈希即使一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆