[英]How do I replace a value included in a hash?
I have an array of hashes: 我有一系列哈希:
arr = [
{:key1=>"foo one bar", :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
CONTAINS "one". 我想搜索如果:key
“ one” "replaced"
:key1
的值替换为"replaced"
”。
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"}
]
I tried using include?
我尝试使用include?
from my previous post and replies in " Replace one matched value in a hash with another " but to no avail. 从我以前的帖子中获得并回复“ 用另一个替换哈希中的一个匹配值 ”,但无济于事。
These will get an EXACT match: 这些将获得完全匹配:
arr.each{|item| item[:key1] = "replaced" if item[:key1]=="one"}
as will: 将:
p arr.each {|x| x[:key1] = "replaced" if x.values_at(:key1) == "one"}
but I need it to just INCLUDE the string term. 但我只需要包含字符串项即可。
arr = [
{:key1=>"foo one bar", :key2=>"two", :key3=>"three"},
{:key1=>"four", :key2=>"five", :key3=>"six"},
{:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]
arr.each {|x| x[:key1] = 'replaced' if x[:key1].include? 'one'}
p arr
Output: 输出:
[{:key1=>"replaced", :key2=>"two", :key3=>"three"}, {:key1=>"four", :key2=>"five", :key3=>"six"}, {:key1=>"seven", :key2=>"eight", :key3=>"nine"}]
您可以使用=~
查找字符串中包含单词one
的模式,例如:
arr.each{|item| item[:key1] = "replaced" if item[:key1] =~ /one/ }
A couple tricks can help create tight, but understandable, code. 几个技巧可以帮助创建紧凑但易于理解的代码。 Starting with: 从...开始:
arr = [
{:key1=>"foo one bar", :key2=>"two", :key3=>"three"},
{:key1=>"four", :key2=>"five", :key3=>"six"},
{:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]
I can use: 我可以用:
arr.map!{ |h|
h[:key1][/\b one \b/x] ?
h.merge(:key1 => 'replaced') :
h
}
Which, after running, looks like: 运行后,其外观如下:
[
[0] {
:key1 => "replaced",
:key2 => "two",
:key3 => "three"
},
[1] {
:key1 => "four",
:key2 => "five",
:key3 => "six"
},
[2] {
:key1 => "seven",
:key2 => "eight",
:key3 => "nine"
}
]
map!
, like map
, needs a return value otherwise it'd return a nil in that position in the iteration. 与map
一样,需要一个返回值,否则它将在迭代中的该位置返回nil。 A ternary statement fits this nicely. 一个三元语句非常适合。 Keeping ternary statements looking nice in Ruby is more difficult than in a language like Perl, which I think is a large reason so many people avoid them. 在Ruby中保持三元语句看起来比在Perl这样的语言中困难得多,我认为这是很多人避免使用它们的主要原因。 We can format a ternary using trailing operators though, which helps us break the statements into separate lines, improving readability. 不过,我们可以使用尾随运算符来格式化三进制,这有助于我们将语句分成几行,从而提高可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.