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?
Try to use the following code to see if it solves your problem
arr.each { |item| item[:key1] = "replaced" if item[:key1] == "one" }
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"}]