Skip to content

Instantly share code, notes, and snippets.

@bitmaybewise
Last active August 29, 2015 14:14
Show Gist options
  • Save bitmaybewise/08ef04817a535042a904 to your computer and use it in GitHub Desktop.
Save bitmaybewise/08ef04817a535042a904 to your computer and use it in GitHub Desktop.
Ruby's pattern matching
# pattern matching on blocks
def print_break(msg)
puts '-' * 50, msg
end
print_break 'normal params'
block = -> (one, two) { p one, two }
block.call(1, 2)
# 1
# 2
print_break 'splat params'
block = -> (*args) { p args }
block.call(3, 4)
# [3, 4]
print_break 'normal params mixed with splat'
block = -> (head, *tail) { p head, tail }
block.call(5, 6, 7, 8)
# 5
# [6, 7, 8]
print_break 'normal params mixed with splat ignoring a value'
block = -> (_, *tail) { p tail }
block.call(5, 6, 7, 8)
# [6, 7, 8]
print_break 'splat mixed in the middle'
block = -> (first, *middle, last) { p first, middle, last }
block.call(5, 6, 7, 8)
# 5
# [6, 7]
# 8
print_break 'splat mixed in the middle'
block.call(5, 8)
# 5
# []
# 8
print_break 'assignments'
_, *tail = [1, 2, 3, 4]
p tail
head, _ = [1, 2, 3,4]
p head
*init, _ = [1, 2, 3,4]
p init
print_break 'tuples'
[
["First Name", "Hercules"],
["Last Name", "Merscher"]
].each do |(key, value)|
puts "#{key}: #{value}"
end
# First Name: Hercules
# Last Name: Merscher
{ first_name: "Hercules", last_name: "Merscher" }.each do |(key, value)|
puts "#{key}: #{value}"
end
# first_name: Hercules
# last_name: Merscher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment