ruby 替换数组中的单个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26415380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace a single element in an array
提问by Lasonic
I have an array with unique elements. Is there a way to replace a certain value in it with another value without using its index value?
我有一个包含唯一元素的数组。有没有办法在不使用索引值的情况下用另一个值替换其中的某个值?
Examples:
例子:
array = [1,2,3,4]
if array.include? 4
# "replace 4 with 'Z'"
end
array #=> [1,2,3,'Z']
hash = {"One" => [1,2,3,4]}
if hash["One"].include? 4
# "replace 4 with 'Z'"
end
hash #=> {"One" => [1,2,3,'Z']}
回答by Johnson
p array.map { |x| x == 4 ? 'Z' : x }
# => [1, 2, 3, 'Z']
回答by sawa
You can do it as:
你可以这样做:
array[array.index(4)] = "Z"
If the element is not necessarily in the array, then
如果元素不一定在数组中,则
if i = array.index(4)
array[i] = "Z"
end
回答by Wayne Conrad
You can use Array#map
您可以使用Array#map
array = array.map do |e|
if e == 4
'Z'
else
e
end
end
to edit the array in place, rather than creating a new array, use Array#map!
要就地编辑数组,而不是创建新数组,请使用Array#map!
If you have more than one thing you want to replace, you can use a hash to map old to new:
如果您要替换的东西不止一件,您可以使用散列将旧的映射到新的:
replacements = {
4 => 'Z',
5 => 'five',
}
array = array.map do |e|
replacements.fetch(e, e)
end
This make uses of a feature of Hash#fetch, where if the key is not found, the second argument is used as a default.
这利用了Hash#fetch的一个特性,如果找不到键,则使用第二个参数作为默认值。
回答by Matheus Moreira
A very simple solution that assumes there will be no duplicates and that the order doesn't matter:
一个非常简单的解决方案,假设不会有重复项并且顺序无关紧要:
hash = { 'One' => [1, 2, 3, 4] }
hash['One'].instance_eval { push 'Z' if delete 4 }
instance_evalsets the value of selfto the receiver (in this case, the array [1,2,3,4]) for the duration of the block passed to it.
instance_evalself在[1,2,3,4]传递给它的块的持续时间内将 的值设置为接收器(在本例中为数组)。

