Monday, November 20, 2006

Returning multiple results from a Ruby method

While it is preferable to have a method call return a single value, sometimes it is necessary to return multiple results. Returning an array or hash works for this purpose, array results can be received into individual variables.

For example, consider a method that returns a boolean success/failure indicator, along with an integer representing the number of items having that status. The following examples show use of an array, and use of a hash, to return the results:

1. Return the results as an array, receive the values in a list of variables.
Return the results (in this case true, and 23):

class MyClass
def some_method
[true, 23]
end
end

Receive the results in separate variables:

my_object = MyClass.new
status, counter = my_object.some_method

2. Return the results as a hash:
Return the results in a hash (in this case with keys of :status and :counter):

class MyClass
def some_method
{:status => true, :counter => 23}
end
end

Use the results:

my_object = MyClass.new
results = my_object.some_method

#the results are now in the hash
puts results[:status]
puts results[:counter]

1 comment:

Stephan said...

Well, you could also create a Struct, or OpenStruct (Ruby Standard Library Documentation for OpenStruct).

Anyway, the return values are very cloely related - they're returned by the same method after all, which can be the sign that they "want to be a new class".