Cisplatin Cisplatin - 1 month ago 8
Ruby Question

How to call a function that mutates a variable in Ruby?

The standard method would be something like

foo = bar(foo)


But I'd like some kind of way to simply write

bar(foo)


That would change the value of
foo
like the first line. In C++ I could do this with pointers, but with Ruby I don't know how to.

Answer

This is not possible in Ruby. You'll have to write foo = bar(foo).

Another option would be to let foo be a mutable object. Then bar could call methods on it to mutate it. For example, if foo is a String, Hash, or Array, bar could call foo.replace to modify the object that foo refers to.

Comments