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

后端 未结 6 461
天涯浪人
天涯浪人 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:16

    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! :)

提交回复
热议问题