Matt Perejda
Matt Perejda

Reputation: 531

Naming Var using Var

I'm trying to create arrays dynamically and am messing with this code, but I'm not getting anywhere.

Starting with locations:

locations = {"boston" => 1, "new_york" => 2 , "miami" => 3}

And using:

locations.each {
|city, id|  puts "#{city}_angels"
}

The desired outcome is to initialize three arrays: boston_angels, new_york_angels, miami_angels.

Upvotes: 0

Views: 51

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

The question has nothing to do with the values of the hash location, so let's start with:

cities = locations.keys
  #=> ["boston", "new_york", "miami"]

Three other ways to do this:

#1

Hash[cities.map { |c| [c, []] }]
  #=> {"boston"=>[], "new_york"=>[], "miami"=>[]}

With Ruby 2.1+ you can write Hash[arr] as arr.to_h.

#2

cities.reduce({}) { |h,city| h.merge({ city=>[] }) }

#3

h = Hash.new { |h,k| h[k] = [] }
h.values_at(*cities)
h
  #=> {"boston"=>[], "new_york"=>[], "miami"=>[]}

Upvotes: 1

Chris Heald
Chris Heald

Reputation: 62668

Per the comments on the question, there are lots of way to construct a hash from a source enumerable. each_with_object is one of my favorites:

locations.keys.each_with_object({}) {|city, out| out[city] = [] }

inject/reduce is another option:

locations.keys.inject({}) {|h, city| h[city] = []; h }

You could also create an array of [city, []] arrays, then convert it to a hash:

Hash[*locations.flat_map {|city, id| [city, []] }]

Or if you're using Ruby 2.1:

locations.keys.map {|k| [k, []] }.to_h

Upvotes: 2

Related Questions