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
You can return only one value in Java. If needed you can return multiple values using array or an object.
Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns.
We know that the syntax of functions in C doesn't allow us to return multiple values.
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.
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
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]
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