Returning two items: Array vs. Struct

I have a calculate(data) method that returns two values. One is the class ( Float ), and the other is the 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?

+4
source share
3 answers

The shape of the array is more idiomatic. In fact, you can do this with Ruby's built-in multiple return mechanism:

 def calculate(data) ... return grade, details end grade, details = calculate(data) 
+4
source

For the method to be used inside the library, your first option is more efficient and would be a good choice. For the method intended for the user to use the library, something along the lines of your second option has a more desirable interface and should be used.

+4
source

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 defused Hash#each to yield a Struct.new(:key, :value) instead of a two-element Array and almost all I had to do to get most of the missed RubySpecs was to implement to_ary .

+3
source

Source: https://habr.com/ru/post/1498452/


All Articles