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

后端 未结 6 474
天涯浪人
天涯浪人 2020-12-08 06:56

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.

6条回答
  •  情书的邮戳
    2020-12-08 07:29

    The each method never changes the object it works on.

    You should use map! method instead:

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

提交回复
热议问题