Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 是否有一种干净的方法来访问哈希数组中的哈希值?_Ruby - Fatal编程技术网

Ruby 是否有一种干净的方法来访问哈希数组中的哈希值?

Ruby 是否有一种干净的方法来访问哈希数组中的哈希值?,ruby,Ruby,在此代码中: arr = [ { id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }] arr.map { |h| h[:id] } # => [1, 2, 3] 有没有更干净的方法从这样的散列数组中获取值 ,我想知道是否有红宝石的等价物。如果你不介意猴子修补,你可以自己去拔: arr = [{ id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3

在此代码中:

arr = [ { id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }]
arr.map { |h| h[:id] } # => [1, 2, 3]
有没有更干净的方法从这样的散列数组中获取值


,我想知道是否有红宝石的等价物。

如果你不介意猴子修补,你可以自己去拔:

arr = [{ id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }]

class Array
  def pluck(key)
    map { |h| h[key] }
  end
end

arr.pluck(:id)
=> [1, 2, 3]
arr.pluck(:body)
=> ["foo", "bar", "foobar"]

此外,它看起来像是,和其他人。

现在rails支持
数组。从盒子中取出
。它已由本组织实施

其实施方式如下:

def pluck(key)
  map { |element| element[key] }
end

因此,无需再对其进行定义:)

虽然我觉得
pulk
是一个有用的添加,但在Ruby中,在“更通用的解决方案”链接中添加
invoke
语义是相当愚蠢的,因为
Symbol\u-proc
为您解决了这个问题<代码>[1,2,3,4]。map&:to_s
无需修补。符号to_proc
/
[]map&:method_name
快捷方式对
散列[key]
没有帮助,因为
散列[]
需要键参数。