2

我有一个哈希数组:

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

我想搜索并替换:key1if "replaced"=:key的值"one"

然后生成的数组将读取:

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

谁能指出我正确的方向?

4

2 回答 2

2

尝试使用以下代码,看看它是否解决了你的问题

arr.each { |item| item[:key1] = "replaced" if item[:key1] == "one" }
于 2013-04-18T07:55:35.940 回答
0
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"}

或者

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

输出:

[{:key1=>"replaced", :key2=>"two", :key3=>"three"}, {:key1=>"four", :key2=>"five", :key3=>"six"}, {:key1=>"seven", :key2=>"eight", :key3=>"nine"}]
于 2013-04-18T08:15:31.620 回答