Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return two and more values from a method

Tags:

ruby

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 
like image 674
ceth Avatar asked Dec 25 '09 11:12

ceth


People also ask

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.

Can you return two things from a method in Java?

Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns.

Can I return 2 values from a function in C?

We know that the syntax of functions in C doesn't allow us to return multiple values.

How can I return multiple values from a function in Java?

You can return an object of a Class in Java. If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class. If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc.


2 Answers

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 
like image 57
Aditya Mukherji Avatar answered Oct 14 '22 10:10

Aditya Mukherji


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] 
like image 22
Jörg W Mittag Avatar answered Oct 14 '22 10:10

Jörg W Mittag