Replace one matched value in a hash with another

六月ゝ 毕业季﹏ 提交于 2019-12-24 01:43:11

问题


I have an array of hashes:

arr = [
  {:key1=>"one", :key2=>"two", :key3=>"three"},
  {:key1=>"four", :key2=>"five", :key3=>"six"},
  {:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]

and I would like to search through and replace the value of :key1 with "replaced" if :key = "one".

The resultant array would then read:

arr = [
  {:key1=>"replaced", ;key2=>"two", :key3=>"three"},
  {:key1=>"four", ;key2=>"five", :key3=>"six"},
  {:key1=>"seven", ;key2=>"eight", :key3=>"nine"}
]

Can anyone point me in the right direction?


回答1:


Try to use the following code to see if it solves your problem

arr.each { |item| item[:key1] = "replaced" if item[:key1] == "one" }



回答2:


arr = [
  {:key1=>"one", :key2=>"two", :key3=>"three"},
  {:key1=>"four", :key2=>"five", :key3=>"six"},
  {:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]

p arr.each {|x| x[:key1] = "replaced" if x.assoc(:key1).include? "one"}

or

p arr.each {|x| x[:key1] = "replaced" if x.values_at(:key1) == "one"}

Output:

[{:key1=>"replaced", :key2=>"two", :key3=>"three"}, {:key1=>"four", :key2=>"five", :key3=>"six"}, {:key1=>"seven", :key2=>"eight", :key3=>"nine"}]


来源:https://stackoverflow.com/questions/16077357/replace-one-matched-value-in-a-hash-with-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!