Returning Multiple Values

But what about those occasions when you need a method to return more than one value? In other program languages, you may be able to “fake” this by passing arguments by reference (pointers to the original data items) rather than by value (a copy of the data); when you alter the values of “by reference” arguments, you alter the original values without explicitly having to return any values to the calling code.

Ruby doesn’t make a distinction between “by reference” and “by value,” so this technique is not available to you (though you will see some exceptions to the rule shortly). However, Ruby is capable of returning multiple values all in one go, as shown here:

return_many.rb

def ret_things
    greeting = "Hello world"
    a = 1
    b = 2.0
    return a, b, 3, "four", greeting, 6 * 10
end

Multiple return values are placed into an array. If you were to evaluate ret_things.class, Ruby would inform you that the returned object is an Array. You could, however, explicitly return a different collection type such as a Hash:

def ret_hash
    return {'a'=>'hello', 'b'=>'goodbye', 'c'=>'fare thee well'}
end
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.18.218