Created
May 5, 2022 23:23
-
-
Save JoshCheek/375c8510659ee1b8c788fc0e03052aa0 to your computer and use it in GitHub Desktop.
Example of how to deal with Ruby case statements
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
| # https://twitter.com/josh_cheek/status/1522312126995611651 | |
| def UnmatchedCase(...) | |
| UnmatchedCase.new(...) | |
| end | |
| class UnmatchedCase < RuntimeError | |
| PENDING = Struct.new(:inspect).new('(PENDING)') | |
| attr_reader :description, :value | |
| def initialize(description, value = PENDING) | |
| @description, @value = description, value | |
| super "#{description}: #{value.inspect}" | |
| end | |
| def ===(case_value) | |
| initialize description, case_value | |
| set_backtrace caller.drop(1) | |
| raise self | |
| end | |
| end | |
| # Note that the colons in the original tweet did not work for me. I do remember | |
| # something like that in the past, but looking at `parse.y`, it does not seem | |
| # to be a thing: https://github.com/ruby/ruby/blob/v3_1_2/parse.y#L4053 | |
| def describe_music(year) | |
| case year | |
| when 1970..1979 then 'disco' | |
| when 1980..1989 then 'eighties' | |
| when 1990..1999 then 'dance' | |
| when 2000.. then 'RnB' | |
| when UnmatchedCase('Unknown musical genre time frame') | |
| end | |
| end | |
| describe_music 2020 # => "RnB" | |
| describe_music 1994 # => "dance" | |
| describe_music 1983 # => "eighties" | |
| describe_music 1970 # => "disco" | |
| describe_music 1955 # => UnmatchedCase: Unknown musical genre time frame: 1955 | |
| # ~> UnmatchedCase | |
| # ~> Unknown musical genre time frame: 1955 | |
| # ~> | |
| # ~> program.rb:38:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment