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.
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.
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.
You can't return two values. However, you can return a single value that is a struct that contains two values.
You can return only one value in Java. If needed you can return multiple values using array or an object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With