Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning two elements: Array vs. Struct

Tags:

ruby

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?

like image 395
Guarana Joe Avatar asked Dec 20 '22 01:12

Guarana Joe


2 Answers

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)
like image 148
Chris Heald Avatar answered Jan 06 '23 01:01

Chris Heald


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.

like image 25
sawa Avatar answered Jan 06 '23 00:01

sawa