0
Hash1 = {
    map1: {city: 'Berlin', country: 'Germany'},
    map2: {city: 'Toronto', country: 'Canada'},
    map3: {city: 'Boston', country: 'USA' }
}

Okay so I want to build a hash that looks as follows:

newHash = {
    Berlin: 'map1',
    Toronto: 'map2',
    Boston: 'map3' 
}

How do I loop through Hash1 and build newHash.

Hash1.each_with_object({}) do |(key, value), acc|
  # what do I do inside this loop?
end
1
  • Why do you want to convert the strings to symbols and vice versa? Commented Aug 22, 2017 at 9:02

4 Answers 4

2
Hash1.map { |k, v| [v[:city].to_sym, k.to_s] }.to_h
#⇒ {:Berlin=>"map1", :Toronto=>"map2", :Boston=>"map3"}
Sign up to request clarification or add additional context in comments.

Comments

1
data = {
  map1: {city: 'Berlin', country: 'Germany'},
  map2: {city: 'Toronto', country: 'Canada'},
  map3: {city: 'Boston', country: 'USA' }
}

new_data = data.reduce({}) { |h, (k, v)| h[v[:city].to_sym] = k.to_s; h }

puts new_data #=> {:Berlin=>"map1", :Toronto=>"map2", :Boston=>"map3"}

3 Comments

Consider to use each_with_object here. Besides ugly ; h, reduce recreates the object on each iteration.
@mudasobwa reduce doesn't recreate the object. It passes the object which is returned by the block into the next iteration. So if the block returns the same object (like h above), no additional objects will be created. (nonetheless, each_with_object would be the better tool)
@Stefan oh, indeed, I stated it wrong, thanks for the correction.
0
output = {}
hash.each do |key, value|
  output[:"#{value[:city]}"] = key.to_s
end

puts output
# {:Berlin=>"map1", :Toronto=>"map2", :Boston=>"map3"}

For the exact output style, you have to use the Ruby 1.9 or higher version.

1 Comment

You are abusing each with preliminary created local variable. Use each_with_object instead.
0

I'm showing just one of many methods below

new_hash = Hash.new
Hash1.each do |key, value|
     new_hash[value[:city]] = key
end

3 Comments

Please avoid abusing each with preliminary created local variable instead of map/reduce. Also, value['city'] would be nil.
Can you please elaborate why using each, a bad idea here?
each is for enumerating. reduce/each_with_object is for reducing. The code is semantically incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.