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!
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With