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

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

    Map is probably the best way, but you can change the string in-place too.

    > a = "hello"
    > puts a
    => hello
    
    > a.replace("hi")
    > puts a
    => hi
    

    changes the internal value of the string. For example, your code could become :

    x = %w(hello there world)
    x.each { |e| if (e == "hello"); e.replace("hi") end; }
    

    but this is much nicer :

    x = %w(hello there world)
    x.map! { |e| e == "hello" ? "hi" : e }
    

提交回复
热议问题