简体   繁体   中英

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 (ie, 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 this 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).

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM