user3735671
user3735671

Reputation: 41

How to return two separate arrays of keys and values

Please explain how this piece of code can return two arrays.

def keysAndValues(data)
  [data.keys, data.values]
end

Upvotes: 0

Views: 178

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

Ruby supports parallel assignment. This is a simple example:

foo, bar = 1, 2
foo # => 1
bar # => 2

Your method is returning two values inside an array:

keys_and_values(
  {
    a: 1,                    
    b: 2                     
  }                          
).size # => 2

which are assigned via = to the two values on the left side of the equation. The values in the array are references to where the keys and values sub-arrays are located:

foo, bar = keys_and_values(
  {
    a: 1,                    
    b: 2                     
  }                          
)

foo.object_id  # => 70159936091440
bar.object_id  # => 70159936091420

Ruby isn't unique with supporting parallel assignment; It is used in other languages too. Any decent Ruby manual will talk about this. It's good to understand because the assignment to variables, or passing multiple parameters to methods is something you'll encounter repeatedly in Ruby. Do a search for more information.

Also, in Ruby we don't name methods using camelCase, such as "keysAndValues". Instead we use snake_case: keys_and_values.

Upvotes: 1

twonegatives
twonegatives

Reputation: 3438

keysAndValues method does return a single array (of two arrays inside of it), but its output can be interpreted as two arrays. Let me explain:

single_array = ["hello", "world"]
puts single_array # => ["hello", "world"]
first_element, second_element = single_array
puts first_element # => "hello"
puts second_element # => "world"

The reason this notation is possible is the implementation of Ruby's assignment (=) operator. Thus, calling a, b = keysAndValues(data) makes both variables a and b filled. But beware, although the outcome technically makes sense this might be unexpected in some situations:

first, second = 1 # first is 1, second is nil

There are also some other uses for multiple assignment, consider the following case:

a, b, *c = [1, 2, 3, 4] # note the asterisk symbol here
puts a # => 1
puts b # => 2
puts c # => [3,4]

Upvotes: 1

Related Questions