Reputation: 191
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.
Upvotes: 1
Views: 56
Reputation: 18772
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)
Upvotes: 0
Reputation: 1113
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']
Upvotes: 2
Reputation: 6100
user_names = users.map {|obj| obj[:name]}
#user_names = ["chris", "john"]
Will give you Array with all names
Upvotes: 1