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 2s 'x' , can't this. tried:

1st attempt: 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

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -