Reputation: 3105
I am currently using the following to get an array of a certain field in a table:
Classrooms.all.map(&:teacher_name)
This returns the following:
["James", "Josh", "Peter"]
What I want is a hash instead so something like the following where I can include the teacher_id:
{"James" => "1", "Josh" => "2", "Peter" => "3"}
I tried using Classrooms.all.map(&:teacher_name, &:teacher_id)
but it gives me a syntax error.
Thanks!
Upvotes: 4
Views: 4408
Reputation: 2905
Ruby 2.6.0 enables a shorter syntax:
Classrooms.all.to_h { |t| [t.teacher_name, t.teacher_id] }
Upvotes: 3
Reputation: 112
Another alternative is not to use each at all. Use each_with_object instead. It is designed for what you are trying to do.
Classrooms.all.each_with_object({}) { |c, hash| hash[c.teacher_name] = c.teacher_id }
Upvotes: 1
Reputation:
Do it the old-fashioned way:
pairs = Classrooms.all.map {|t|
[t.teacher_name, t.teacher_id] # [key, value]
}
hash = Hash[pairs] # in /old/ ruby: Hash[*pairs.flatten]
.. or whatnot.
See In Ruby, how do I make a hash from an array?
Upvotes: 5