Last active
August 25, 2020 23:12
-
-
Save serradura/499e403e64d53dfcb8c891dfff594e20 to your computer and use it in GitHub Desktop.
Pattern matching for old Rubies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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