简体   繁体   中英

Ruby: Call Get Value From Hashes In Array

This is probably a stupid one, but I'm missing something here...

I have this

users = [{name: "chris"}, {name: "john"}]

This works

users.map do |obj|
   puts obj[:name]
end

I want to do this

user.map(&:name)

tried the symbol to proc in many different ways with no luck. I can't think of a way to do this that makes sense, but I feel there is one.

To be able to use user.map(&:name) you need a name method on every object inside your array.

Hash doesn't have a name method, but you could implement it (Don't do this, it's just an example):

class Hash
  def name
    self[:name]
  end
end

But a much better solution is to define a class for your names. Since this case is very simple a Struct will do.

Assuming these names belong to users or customers, you could do something like this:

User  = Struct.new(:name)
users = []

users << User.new('chris')
users << User.new('john')

user.map(&:name) # ['chris', 'john']
user_names = users.map {|obj| obj[:name]}
#user_names = ["chris", "john"]

Will give you Array with all names

You could use following syntax that is based on lambda and proc :

users = [{name: "chris"}, {name: "john"}]
p users.map(&->(i){i[:name]})

or

users = [{name: "chris"}, {name: "john"}]
p users.map(&proc{|i| i[:name]})

or

users = [{name: "chris"}, {name: "john"}]
name = proc{|i| i[:name]}
p users.map(&name)

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