It's not a big story, but I was pretty confused at first.
For example, suppose you have the following hash.
key | value |
---|---|
Taro | Miyagi |
Jiro | Aomori |
Hanako | Okinawa |
This can be simply written as hash = {"Taro "=>" Miyagi "," Jiro "=>" Aomori "," Hanako "=>" Okinawa "}
, but there is also such a hash. And.
key | value |
---|---|
Miyagi | 400 yen |
Aomori | 700 yen |
Okinawa | 1200 yen |
I'm not sure if the shipping cost for each prefecture is about this, so please forgive me for the random numbers, but it looks like a table like the shipping cost for each prefecture. This is also like ref = {"Miyagi "=> 400," Aomori "=> 700," Okinawa "=> 1200}
.
As a reminder, I couldn't find a description of the case where I wanted to convert it to a hash of a name and shipping pair.
I used to do the annoying thing of converting it to a two-dimensional array and then back to the hash again, but it was better to use transform_values
, a method that allows you to change all the hash values directly. Thank you for telling me.
list = hash.transform_values{ |x| ref[x] }
p list
# { "Taro" => 400 , "Jiro" => 700, "Hanako" => 1200 }
Or
hash.transform_values(&ref)
But it seems to be okay. smart!
list = hash.to_a.each{|x| x[1] = ref[x[1]]}.to_h
p list
# { "Taro" => 400 , "Jiro" => 700, "Hanako" => 1200 }
I want to process them in order, so I just need to convert them to a two-dimensional array with to_a
, put the hash value of ref in the second (x [1]) in order, and finally convert it to a hash.
It's simple, but it's surprisingly confusing. I think there might be an easier way (there was).
Recommended Posts