ruby - Replace method on Array -
ruby - Replace method on Array -
i have array:
array = [1,2,3,4,5,2,6,7,2,8,9,2,10]
i want replace 2
s 'x'
, can't this. tried:
array.select{|num| num == 2? num = 'x' : num}
2nd attempt: array.select{|num| num == 2}.replace(['x'])
i'm making harder is.
i'd use:
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!
changes array
, if don't want alter array itself:
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]
ruby arrays
Comments
Post a Comment