Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use map to get a hash instead of an array?

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!

like image 997
Goalie Avatar asked Oct 19 '25 01:10

Goalie


1 Answers

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?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!