Skip to content

Instantly share code, notes, and snippets.

@serradura
Last active August 25, 2020 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serradura/499e403e64d53dfcb8c891dfff594e20 to your computer and use it in GitHub Desktop.
Save serradura/499e403e64d53dfcb8c891dfff594e20 to your computer and use it in GitHub Desktop.
Pattern matching for old Rubies
def on(arg, spec)
track, result = arg.to_a[0]
type, data = result.to_a[0]
hook = spec.fetch(track, {})[type]
return unless hook
keys = hook.parameters.map(&:last)
keys.empty? ? hook.call : hook.call(*data.values_at(*keys))
end
result = { success: { print_name: { first: 'Rodrigo', last: 'Serradura' } } }
on(
result,
success: {
greet: -> (first, last) { puts "Hi #{first} #{last}!" },
print_name: -> (last, first) { puts "#{last}, #{first}!" }
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment