简体   繁体   English

红宝石哈希值从一个密钥交换到另一个

[英]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? 有人对我如何将哈希值重新映射到不同的键有Ruby建议吗? 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): 并想要得到它(即,“ present”,“ first”和“ subject”,“ second”的值已切换):

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). 编辑: from.values_rearranged_in_any_way_you_like应该是from.values以您需要的方式排序(我假设您确实有一种希望的方式来对它们进行排序以进行重新排列)。

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: 或者,如果您只想将em上移一项:

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. 不确定您是否应该在红宝石中重新映射巨大的哈希值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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