Blocks accept array elements as multiple parameters? How?


Sorry for the confusing title.

I am doing one of the quizzes and am surprised by the solution.

people = [["Lebron", "cool dude"], ["Bieber", "jerk face"]]

Iterate through the people array and print the following sentences: Lebron is a cool dude Bieber is a jerk face

So it’s easy and I solved it like this:

people.each do |person|
  puts "#{person[0]} is a #{person[1]}"

I was surprised that this can be done like this as well:

people.each do |first_name, description|
  puts "#{first_name} is a #{description}"

I am wandering what is this called (substituting array for it’s individual elements) and when can it be done in ruby (in what other situations except this one)?


A block can take as many argument as you want and any not passed in are just assigned nil.

people = ["me", "you"]

people.each do |person, whatever, whatever2|
  #do something

This is valid code although it serves no purpose because whatever, and whatever2 would just be assigned nil as only one argument is passed into the each iterator.

When you call each on an array of arrays each iteration is passed something like ["Lebron", "cool dude"] and therefore you can assign each to a block variable. It’s just a quirk of how Ruby handles parameters passed into blocks, they are deconstructed so maybe Google ‘ruby block deconstructing’ or something.

You can do the same thing if you iterate a hash.