简体   繁体   中英

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. Even if params is a hash, please tell me if anyone knows how to do this?

Given

params = [{id: 1, name: 'hoge'}, {id: 2, name: 'fuga'}]

As emaillenin says, you can do:

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. But, you can't do:

params.map{ |u| u.name }

If u is a 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 !

params = [{id: 1, name: 'hoge'}, {id: 2, name: 'fuga'}]
params.pluck(:name)

=> ["hoge", "fuga"]

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM