I have a method calculate(data) that returns two values. One is a grade (Float) and another is details (Hash). Comparing the following two options, is there a preferred way?
def calculate(data)
  ...
  [grade, details]
end
grade, details = calculate(data)
vs.
def calculate(data)
  ...
  Result.new(grade, details)
end
result = calculate(data)
grade = result.grade
details = result.details
What is more idiomatic in Ruby?
The array form is more idiomatic. In fact, you can do it via Ruby's built-in multiple returns mechanism:
def calculate(data)
  ...
  return grade, details
end
grade, details = calculate(data)
                        For a method intended to be used internal to a library, your first option is more efficient and would be a good choice. For a method intended to be used by a user of a library, something along the lines of your second option has more desirable interface, and should be used.
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