ruby hash swap values from one key to another
Does anyone have Ruby advice on how would I go about re-mapping the values within a hash to different keys? Say I have this
from => {"first"=>30, "wanted"=>27, "second"=>45, "subject"=>68, "present"=>85}
and wanted to get this (i.e., values for "present","first" and "subject","second" have been switched):
to => {"first"=>85, "wanted"=>27, "second"=>68, "subject"=>45, "present"=>30}
I want to do thi开发者_如何学Pythons over a large data set.
# this is your starting hash:
from = {"first"=>30, "wanted"=>27, "second"=>45, "subject"=>68, "present"=>85}
# this is your replacement mapping:
map = {'present' => 'first', 'subject' => 'second'}
# create complete map by inverting and merging back
map.merge!(map.invert)
# => {"present"=>"first", "subject"=>"second", "first"=>"present", "second"=>"subject"}
# apply the mapping to the source hash:
from.merge(map){|_, _, key| from[key]}
# => {"first"=>85, "wanted"=>27, "second"=>68, "subject"=>45, "present"=>30}
You don't provide enough context, but you could do something like
to = Hash[from.keys.zip(from.values_rearranged_in_any_way_you_like)]
Edit: from.values_rearranged_in_any_way_you_like
is supposed to be from.values
sorted in the way you need (I'm assuming you do have a desired way to sort them for rearrangement).
Well, here's a simple little algorithm. I don't know how efficient it would be, but it should work.
class Hash
def swap_vals!(new_key_maps)
new_key_maps.each do |key1, key2|
temp = self[key1]
self[key1] = self[key2]
self[key2] = temp
end
end
end
You could do something like this:
keys = @hash.keys
values = @hash.values
then you could swap entries of the 'values' array (or 'keys' array)
values[0], values[4] = values[4], values[0]
...
or if you only wanted to shift em up by one item:
values.rotate (ruby 1.9)
you can also perform push/pop, shift/unshift operations or sort the values To create the hash do:
hsh = Hash.new
keys.size.times do |i|
hsh[ keys[i] ] = values[i]
end
Keep it simple, use merge:
from => {"first"=>30, "wanted"=>27, "second"=>45, "subject"=>68, "present"=>85}
to => {"first"=>85, "wanted"=>27, "second"=>68, "subject"=>45, "present"=>30}
from.merge(to)
# => {"first"=>85, "wanted"=>27, "second"=>68, "subject"=>45, "present"=>30}
Not sure you should be remapping enormous hashes in ruby though.
精彩评论