有没有人对我如何将散列中的值重新映射到不同的键有 Ruby 的建议?说我有这个
from => {"first"=>30, "wanted"=>27, "second"=>45, "subject"=>68, "present"=>85}
并且想要得到这个(即,“present”、“first”和“subject”、“second”的值已经交换):
to => {"first"=>85, "wanted"=>27, "second"=>68, "subject"=>45, "present"=>30}
我想对大型数据集执行此操作。
最佳答案
# 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}
关于ruby 哈希将值从一个键交换到另一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6937352/