1

I have an array:

array = [1,2,3,4,5,2,6,7,2,8,9,2,10]

I want to replace all the 2s with 'x' and can't do this. I tried:

  • 1st attempt: array.select{|num| num == 2? num = 'x' : num}
  • 2nd attempt: array.select{|num| num == 2}.replace(['x'])

I'm making this harder than it is.

2
  • What is your question? Commented Oct 21, 2014 at 17:18
  • it was to replace all the 2s in the array with 'x' Commented Oct 21, 2014 at 17:26

1 Answer 1

3

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, but if you don't want to change the 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]
Sign up to request clarification or add additional context in comments.

2 Comments

man, i feel like an idiot... thanks Tin Man! I still have 9 minutes on the accept...
Personally, I prefer a conditional expression over the conditional operator: array.map {|e| if e == 2 then 'x' else e end }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.