1

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.

1
  • When you give an example (generally a good thing), you should show your desired or expected result. It generally clarifies the question and does not take up much space. btw, it was good of you to define the variable users. That allows readers to reference it in comments and answers. All too often the variable is omitted. Commented Dec 30, 2015 at 19:19

3 Answers 3

2

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I thought there might be a some magic that my do that on the fly. But this at least explains it to me. Thanks.
The question is how he can use user.map(&:name) in his code, he literally says 'I want to do this'. Exactly that code, that's not what the other answer is saying at all.
1
user_names = users.map {|obj| obj[:name]}
#user_names = ["chris", "john"]

Will give you Array with all names

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.