Is there a way to modify particular array elements (based on some condition) while traversing it in reverse order in Ruby?
有没有办法在Ruby中以相反的顺序遍历它时修改特定的数组元素(基于某些条件)?
To be more clear lets say,
更清楚地说,
problem is replace even numbers in [1,2,3,4,5] with x
问题是将[1,2,3,4,5]中的偶数替换为x
output should be [1,x,3,x,5] (same array) but replace should happen from right to left..traversing from 5 to 1.
输出应该是[1,x,3,x,5](相同的数组),但是替换应该从右到左发生..从5到1。
Thanks in Advance!
提前致谢!
This works: (arr.length -1).downto(0) { |x| do something with arr[x] }
这适用:(arr.length -1).downto(0){| x |用arr做某事[x]}
3 个解决方案
#1
3
p [1,2,3,4,5].reverse_each.map{|e| e.odd? ? e : e/2} #[5, 2, 3, 1, 1]
#2
1
I understand you want to traverse in reverse order, not get the output also reversed. Maybe this:
我理解你想以相反的顺序遍历,而不是让输出也反转。也许这个:
xs = [1, 2, 3]
xs.reverse_each.with_index { |x, idx| xs[xs.size-1-idx] = x.to_s if x == 2 }
xs #=> [1, "2", 3]
#3
0
I appreciate and love Ruby's humane syntax, but you may want to consider more verbose options such as:
我很欣赏并喜欢Ruby的人性化语法,但您可能需要考虑更详细的选项,例如:
ary = [1,2,3,4,5]
i = ary.count - 1
while i >= 0 do
ary[i] = "x" if ary[i] % 2 == 0
i -= 1
end
puts ary.join(",")
#1
3
p [1,2,3,4,5].reverse_each.map{|e| e.odd? ? e : e/2} #[5, 2, 3, 1, 1]
#2
1
I understand you want to traverse in reverse order, not get the output also reversed. Maybe this:
我理解你想以相反的顺序遍历,而不是让输出也反转。也许这个:
xs = [1, 2, 3]
xs.reverse_each.with_index { |x, idx| xs[xs.size-1-idx] = x.to_s if x == 2 }
xs #=> [1, "2", 3]
#3
0
I appreciate and love Ruby's humane syntax, but you may want to consider more verbose options such as:
我很欣赏并喜欢Ruby的人性化语法,但您可能需要考虑更详细的选项,例如:
ary = [1,2,3,4,5]
i = ary.count - 1
while i >= 0 do
ary[i] = "x" if ary[i] % 2 == 0
i -= 1
end
puts ary.join(",")