Q: Returning two elements: Array vs. Struct 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?

A: 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)


A: 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.

A: The best of both worlds:
Result = Struct.new(:grade, :details) do
  def to_ary; [grade, details] end
end

def calculate(data)
  Result.new(1, 'Two')
end

grade, details = calculate(:ignore)
# => #<struct Result grade=1, details="Two">

grade
# => 1

details
# => 'Two'

As an experiment, I once monkeypatched Hash#each to yield a Struct.new(:key, :value) instead of a two-element Array and pretty much all I had to do to get most of the RubySpecs passing again was to implement to_ary.
