我有一个数组:
array = [1,2,3,4,5,2,6,7,2,8,9,2,10]
我想用2
替换所有'x'
,但不能这样做。我试过了:
array.select{|num| num == 2? num = 'x' : num}
array.select{|num| num == 2}.replace(['x'])
我正在努力做到这一点。
答案 0 :(得分:3)
我会用:
array = [1,2,3,4,5,2,6,7,2,8,9,2,10]
array.map!{ |e| e == 2 ? 'x' : e }
array # => [1, "x", 3, 4, 5, "x", 6, 7, "x", 8, 9, "x", 10]
map!
更改array
,但如果您不想更改数组本身:
foo = array.map{ |e| e == 2 ? 'x' : e }
array # => [1, 2, 3, 4, 5, 2, 6, 7, 2, 8, 9, 2, 10]
foo # => [1, "x", 3, 4, 5, "x", 6, 7, "x", 8, 9, "x", 10]