[英]Fetch the value of a specific key from the hash array
params = [{id: 1, name: 'hoge'}, {id: 2, name: 'fuga'}]
I know I can fetch the values of a specific key in this way. 我知道我可以通过这种方式获取特定键的值。
params.map{ |u| u.name }
=> ["hoge", "fuga"]
But, I wanna do this without block like below, 但是,我想做到以下所示,
params.map(&:name)
If the params is ActiveRecord, I can do in above way. 如果参数是ActiveRecord,则可以按照上述方式进行。 Even if params is a hash, please tell me if anyone knows how to do this?
即使params是哈希值,也请告诉我是否有人知道该怎么做?
Given 给定
params = [{id: 1, name: 'hoge'}, {id: 2, name: 'fuga'}]
As emaillenin says, you can do: 正如emaillenin所说,您可以执行以下操作:
params.map { |p| OpenStruct.new(p) }.map(&:name)
But, if you do: 但是,如果您这样做:
params.map { |p| OpenStruct.new(p).name }
You save an iteration and seven key strokes. 您保存一个迭代和七个按键。 And if you do:
如果您这样做:
params.map { |p| p[:name] }
You save an additional 14 characters. 您另外保存14个字符。 But, you can't do:
但是,您不能执行以下操作:
params.map{ |u| u.name }
If u
is a Hash
. 如果
u
是一个Hash
。 Nor can you do: 您也不能这样做:
params.map(&:name)
If you are using rails, and not vanilla ruby, what you're really looking for is pluck
! 如果您使用的是铁轨,而不是香草红宝石,那么您真正想要的就是
pluck
!
params = [{id: 1, name: 'hoge'}, {id: 2, name: 'fuga'}]
params.pluck(:name)
=> ["hoge", "fuga"]
https://apidock.com/rails/ActiveRecord/Calculations/pluck https://apidock.com/rails/ActiveRecord/Calculations/pluck
params = [{id: 1, name: 'hoge'}, {id: 2, name: 'fuga'}]
params.map { |p| OpenStruct.new(p) }.map(&:name)
# ["hoge", "fuga"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.