S
S
Sergey Blokhin2018-12-04 21:46:12
ruby
Sergey Blokhin, 2018-12-04 21:46:12

Can a method know how many output values ​​are expected from it?

Suppose there is a method that returns two values.

def connect()
  return [1, nil]
end

To get values ​​into different variables, we call the method like this:
a, b = connect() 
# => a == 1
# => b == nil

If you specify only one variable, then an array will fall into it:
a = connect() 
# => a == [1, nil]

Is there a possibility when, when specifying two variables, they would be filled as usual, and when specifying one variable, only the first element of the array would fall into it.
An example, as I want (it will not work in this form):
a = connect() 
# => a == 1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2018-12-04
@TITnet

What's the problem?

def f()
  [1] # или [1, 2], или [1, 2, 3]
end

a, _ = f()
p a # выведет 1 по-любому

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question