Skip to content

Instantly share code, notes, and snippets.

@katafrakt
Last active June 1, 2016 10:52
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 katafrakt/f32c7f0e5add474a13ff7a791e7a7791 to your computer and use it in GitHub Desktop.
Save katafrakt/f32c7f0e5add474a13ff7a791e7a7791 to your computer and use it in GitHub Desktop.
Which pattern-matching syntax is better?
# Which pattern-matching syntax you think is better in Ruby?
#
# Some background:
# - https://github.com/katafrakt/noaidi
# - http://katafrakt.me/2016/02/13/quest-for-pattern-matching-in-ruby/
# - http://katafrakt.me/2016/05/24/refactoring-rails-with-noaidi/
# Syntax 1:
Noaidi.match open_file(path), {
[:ok, File] => ->(file) { process_file(file) },
[:error, Exception] => ->(ex) { handle_file_opening_exception(path, ex) }
}
# or
Noaidi.match open_file(path), {
[:ok, File] => lambda {|file| process_file(file) },
[:error, Exception] => lambda {|ex| handle_file_opening_exception(path, ex) }
}
# Pros:
# - close to syntax from other languages, eg. Elixir
# Cons:
# - Hackish Hash syntax
# - Some editors don't like it (emacs)
# Syntax 2:
Noaidi.match open_file(path) do |m|
m(:ok, File) { |file| process_file(file) },
m(:error, Exception) { |ex| handle_file_opening_exception(path, ex) }
}
# Pros:
# - Using natural Ruby idiom (block)
# - No duplicate rockets/arrows or unnecessary lambda keyword
# - dry-transaction uses similar syntax (http://dry-rb.org/gems/dry-transaction/basic-usage/)
# Cons:
# - I'm not entirely sure it's possible to implement
# - adds some clutter
@denyago
Copy link

denyago commented May 26, 2016

Syntax 2 👍

@ricardohsd
Copy link

Syntax 2 as well

@mPanasiewicz
Copy link

Syntax 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment