Return multiple values from a ruby method

Another day, another bit of crazy ruby syntax. It is preferable (and often best practice) to generally return return one value from any method or function. That said, there are occasions where it does actually make sense to return multiple values. In other languages (and indeed, in ruby too) you can achieve this by returning an array or a dictionary/hash of results. In the case of arrays, Ruby provides this alternative syntax. I am not entirely sure that I personally find this more readable, but it definitely requires less code;

def multireturn
  return ["Hello", "World"]
end

a, b = multireturn    #this is where the magic happens...

puts "return 1: #{a}"
puts "return 2: #{b}"

This would output;

return 1: Hello
return 2: World
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s