Return two and more values from a method

Ruby

Ruby Problem Overview


Is there any possibility to return multiple values from method? Something like this:

def someMethod()
  return ["a", 10, SomeObject.new]
end

[a, b, c] = someMethod

Ruby Solutions


Solution 1 - Ruby

def sumdiff(x, y)
  return x+y, x-y
end
#=> nil

sumdiff(3, 4)
#=> [7, -1]

a = sumdiff(3,4)
#=> [7, -1]
a
#=> [7, -1]

a,b=sumdiff(3,4)
#=> [7, -1]
a
#=> 7
b
#=> -1

a,b,c=sumdiff(3,4)
#=> [7, -1]
a
#=> 7
b
#=> -1
c
#=> nil

Solution 2 - Ruby

Ruby has a limited form of destructuring bind:

ary = [1, 2, 3, 4]
a, b, c = ary
p a # => 1
p b # => 2
p c # => 3

a, b, *c = ary
p c # => [3, 4]

a, b, c, d, e = ary
p d # => 4
p e # => nil

It also has a limited form of structuring bind:

 a = 1, 2, 3
 p a # => [1, 2, 3]

You can combine those two forms like so:

a, b = b, a # Nice way to swap two variables

a, b = 1, 2, 3
p b # => 2

def foo; return 1, 2 end
a, b = foo
p a # => 1
p b # => 2

There's several other things you can do with destructuring / structuring bind. I didn't show using the splat operator (*) on the right hand side. I didn't show nesting (using parantheses). I didn't show that you can use destructuring bind in the parameter list of a block or method.

Here's just an appetizer:

def foo(((a, b, c, d), e, *f), g, *h)
  local_variables.sort.each do |lvar| puts "#{lvar} => #{eval(lvar).inspect}" end
end

foo([[1, 2, 3], 4, 5, 6], 7, 8, 9)
# a => 1
# b => 2
# c => 3
# d => nil
# e => 4
# f => [5, 6]
# g => 7
# h => [8, 9]

Solution 3 - Ruby

Whilst returning multiple values is often useful, I usually find it's a pointer to a new object requirement.

That is, I usually find that those return values are closely tied together in meaning/context and are passed around as such. So in these cases I would create a new object to tie these together. It's a particular code smell I've learnt to recognise.

Solution 4 - Ruby

You can achieve this returning an array too, like

def sumdiff(x, y)
    [x+y, x-y]
end

which seems functionally equivalent to

def sumdiff(x, y)
    return x+y, x-y
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncethView Question on Stackoverflow
Solution 1 - RubyAditya MukherjiView Answer on Stackoverflow
Solution 2 - RubyJörg W MittagView Answer on Stackoverflow
Solution 3 - RubyBrian AgnewView Answer on Stackoverflow
Solution 4 - RubyZack XuView Answer on Stackoverflow