Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Ruby return two values?

Tags:

ruby

Whenever I swap values in an array, I make sure I stored one of the values in a reference variable. But I found that Ruby can return two values as well as automatically swap two values. For example,

array = [1, 3, 5 , 6 ,7] array[0], array[1] = array[1] , array[0] #=> [3, 1]  

I was wondering how Ruby does this.

like image 205
Pete Avatar asked Feb 25 '15 17:02

Pete


People also ask

How can I return 2 values in return?

Summary. JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.

How does return work in Ruby?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.

Can we return two values in return statement?

You can't return two values. However, you can return a single value that is a struct that contains two values.

Can a method can return two or more values?

You can return only one value in Java. If needed you can return multiple values using array or an object.


1 Answers

Unlike other languages, the return value of any method call in Ruby is always an object. This is possible because, like everything in Ruby, nil itself is an object.

There's three basic patterns you'll see. Returning no particular value:

def nothing end  nothing # => nil 

Returning a singular value:

def single   1 end  x = single # => 1 

This is in line with what you'd expect from other programming languages.

Things get a bit different when dealing with multiple return values. These need to be specified explicitly:

def multiple   return 1, 2 end  x = multiple # => [ 1, 2 ] x # => [ 1, 2 ] 

When making a call that returns multiple values, you can break them out into independent variables:

x, y = multiple # => [ 1, 2 ] x # => 1 y # => 2 

This strategy also works for the sorts of substitution you're talking about:

a, b = 1, 2 # => [1, 2] a, b = b, a # => [2, 1] a # => 2 b # => 1 
like image 157
tadman Avatar answered Oct 01 '22 10:10

tadman