Skip to content

Instantly share code, notes, and snippets.

@ksss
Last active February 1, 2021 01:37
Show Gist options
  • Save ksss/9a2869bcfc8a48ef0621cf3ae38bd645 to your computer and use it in GitHub Desktop.
Save ksss/9a2869bcfc8a48ef0621cf3ae38bd645 to your computer and use it in GitHub Desktop.
Pattern match samples
# inspired by https://qiita.com/kentaro/items/477c92a57c8aaf694251
user = {
id: 123_456,
name: "ksss",
profile: {
real_name: "栗原勇樹",
image: {
original: "...",
thumbnail: "...",
}
}
}
def test_user
user => { id: _, name: "ksss", profile: profile }
profile => { real_name: "栗原勇樹", image: image }
image => { original: _, thumbnail: _ }
end
def tuplize
[:ok, yield]
rescue => err
[:error, err]
end
# NoMatchingPatternError
case tuplize { File.open("./notexists.txt") }
in [:ok, file]
begin
# file.read
ensure
file.close
end
end
case tuplize { File.open("./notexists.txt") }
in [:ok, file]
begin
# file.read
ensure
file.close
end
in [:error, error]
# error handling
pp error
end
def fizzbuzz(num)
case [num % 3, num % 5]
in [0, 0]
puts 'FizzBuzz'
in [0, _]
puts 'Fizz'
in [_, 0]
puts 'Buzz'
else
puts num
end
end
(1..20).map(&method(:fizzbuzz))
def keyword(foo:, bar:, baz:)
p foo
p bar
p baz
end
[{foo: 1, bar: 2, baz: 3}, {foo: 10, bar: 20, baz: 30}].each do |obj|
keyword(**obj)
end
# 1
# 2
# 3
# 10
# 20
# 30
class Overload
def method_missing(name, *args)
case [name, args]
in [:hello, []]
puts "hello"
in [:hello, [a]]
puts "hello #{a}"
in [:hello, [a, Integer => i]]
puts("hello #{a}!" * i)
end
end
end
o = Overload.new
o.hello #=> hello
o.hello('ksss') #=> hello ksss
o.hello('ksss', 3) #=> hello ksss!hello ksss!hello ksss!
o.hello('ksss', 'yo') #=> in `method_missing': [:hello, ["ksss", "yo"]] (NoMatchingPatternError)
begin
# I do not know what will happen...
raise [Errno::ENOENT, ZeroDivisionError, KeyError].sample
rescue Errno::ENOENT => err
pp err
rescue ZeroDivisionError => err
pp err
rescue KeyError => err
pp err
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment