Assignment and Parameter Passing

Most of the time, Ruby methods come with two access points—like the doors into and out of a room. The argument list provides the way in; the return value provides the way out. Modifications made to the input arguments do not affect the original data for the simple reason that when Ruby evaluates an expression, the result of that evaluation creates a new object, so any changes made to an argument affect only the new object, not the original piece of data. But there are exceptions to this rule, which I’ll show you now.

Let’s start by looking at the simplest case—a method that takes one value as a named parameter and returns another value:

in_out.rb

def change( x )
    x += 1
    return x
end

On the face of it, you might think ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.