Alex Rivera | Logout

Change value of array element which is being referenced in a .each loop?

Asked 2011-04-13T08:57:19.450
44

How do I get the following to happen: I want to change the value of an array element which is being referenced between pipe characters in a .each loop.

Here is an example of what I want to do, but is not currently working:

x = %w(hello there world)
x.each { |element|
   if(element == "hello") {
       element = "hi" # change "hello" to "hi"
   }
}
puts x # output: [hi there world]

It's hard to look up something so general.

Edit
Report

2 Answers

39

You can get the result you want using collect! or map! to modify the array in-place:

x = %w(hello there world)
x.collect! { |element|
  (element == "hello") ? "hi" : element
}
puts x

At each iteration, the element is replaced into the array by the value returned by the block.

answered 2011-04-13T09:01:24.057
1

This is a way has less lines of code:

  x = %w(hello there world)
  x = x.join(",").gsub("hello","hi").split(",")
  puts x
answered 2012-12-05T23:24:53.150

Your Answer