Goalie
Goalie

Reputation: 3105

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!

Upvotes: 4

Views: 4408

Answers (3)

Timitry
Timitry

Reputation: 2905

Ruby 2.6.0 enables a shorter syntax:

Classrooms.all.to_h { |t| [t.teacher_name, t.teacher_id] }

Upvotes: 3

Jack Christensen
Jack Christensen

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

user166390
user166390

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

Related Questions