更改在 .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屋!
查看全文