Pattern Matching I Love

Pattern Matching I Love

O Pattern Matching é uma funcionalidade que foi adicionada ao Ruby 2.7.0. Ele permite que você faça uma comparação de padrões com um objeto e execute um código com base no padrão de correspondente.

# Friday I'm In Love The Cure.
DAYS_OF_WEEK = %w[monday tuesday thursday friday].freeze

FridayImInLove = -> (day) do
  case day
  in 'monday'                then p "I don't care if Monday's blue"
  in 'tuesday' | 'wednesday' then p "Tuesday's grey and Wednesday too"
  in 'thursday'              then p "Thursday, I don't care about you"
  in 'friday'                then p "It's Friday, I'm in love 🎶"
  in 'saturday'              then p 'Saturday, wait'
  in 'sunday'                then p 'And Sunday always comes too late'
  end
end

DAYS_OF_WEEK.each(&FridayImInLove)

# "I don't care if Monday's blue"
# "Tuesday's grey and Wednesday too"
# "Thursday, I don't care about you"
# "It's Friday, I'm in love 🎶"

Eu tenho usado o Pattern Matching. Ele é muito útil e no meu ponto de vista deixa o código mais elegante e legível.

E você, já usou o Pattern Matching? O quê achou? 😄