Replace one matched value in a hash with another

2019-07-10 08:54发布

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?

标签: ruby arrays hash
2条回答
Luminary・发光体
2楼-- · 2019-07-10 09:26
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"}]
查看更多
来,给爷笑一个
3楼-- · 2019-07-10 09:40

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

arr.each { |item| item[:key1] = "replaced" if item[:key1] == "one" }
查看更多
登录 后发表回答