Last Updated: July 24, 2020
·
1.321K
· jurisgalang

Destructuring to express intent

Suppose you have a Hash of company data keyed by their market symbols:

data = {
  appl: [ "Apple, Inc.",   
          700.09, 
          354.24, 
          705.07, 
          "Tim Cook" ],
  amzn: [ "Amazon, Inc.",  
          257.47, 
          256.74, 
          262.00, 
          "Jeffrey Bezos" ],
  # ...
}

If you wanted to reduce it to a list of company names and their respective CEO's, the following will get the job done:

data.map{ |ticker, details| 
  [ details.first, details.last ] 
}

However, with Ruby's support for destructuring you can make your code's intent clearer at a glance:

data.map{ |ticker, (company, price, wk52hi, wk52lo, ceo)| 
  [ company, ceo ] 
}

And since you don't care for all the other details, you could clarify it even more when you write:

data.map{ |ticker, (company, _, _, _, ceo)| 
  [ company, ceo ] 
}