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.
x = %w(hello there world)
x[index] = "hi" if index = x.index("hello")
x[index] = "hi" if index
or
x = %w(hello there world)
index = x.index("hello") and x[index] = "hi"
But one notice: it will replace only first match. Otherwise use map!
as @SirDarlus suggested
Also you can use each_with_index
x.each_with_index do |element, index|
x[index] = "hi" if element == "hello" # or x[index].replace("hi") if element == "hello"
end
But I still prefer using map!
:)