更改在.each循环中引用的数组元素的值? [英] Change value of array element which is being referenced in a .each loop?
本文介绍了更改在.each循环中引用的数组元素的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何发生以下情况:我想更改在.each
循环中的管道字符之间引用的数组元素的值.
How do I get the following to happen: I want to change the value of an array element which is being referenced between pipe characters in a .each
loop.
以下是我想做的一个例子,但目前不起作用:
Here is an example of what I want to do, but is not currently working:
x = %w(hello there world)
x.each { |element|
if(element == "hello") {
element = "hi" # change "hello" to "hi"
}
}
puts x # output: [hi there world]
很难找到如此笼统的东西.
It's hard to look up something so general.
推荐答案
您可以使用collect!
或map!
就地修改数组来获得所需的结果:
You can get the result you want using collect!
or map!
to modify the array in-place:
x = %w(hello there world)
x.collect! { |element|
(element == "hello") ? "hi" : element
}
puts x
在每次迭代中,该元素都会被块返回的值替换为数组.
At each iteration, the element is replaced into the array by the value returned by the block.
这篇关于更改在.each循环中引用的数组元素的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文