ruby 哈希将值从一个键交换到另一个键

标签 ruby hash dictionary key-value inject

有没有人对我如何将散列中的值重新映射到不同的键有 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/

相关文章:

ruby-on-rails - 如何使类\对象在rails中全局可用?

asp.net - 如何在模拟 ASP.NET 中使用散列密码

javascript - 在 javascript 中从 Blob/文件创建 SHA-256 哈希

python - 循环遍历数据框字典

java - 对象问题。使用构造函数还是不使用构造函数?

python - 通过迭代对数据帧字典进行子集化

ruby-on-rails - 在 Rails 中进行通知

ruby - pg gem : 'Warning: no type cast defined for type "numeric"'

c - C中字符串的MD5哈希

ruby - Windows/Ruby 后台处理