When utilizing the new case ... in pattern matching in Ruby, is there a nice way to prevent binding of nil to a variable?
case method()
in ... # Some cases here
...
in ...
...
in variable # If previous clauses did not match, then capture to variable
puts variable
else # How to prevent that variable also captures nil?
puts "Nil" # -> This is not called if method() returns nil
end
I have found the following two ways but they kind of seem ugly:
1.) Use if qualifier
case method()
in ... # Some cases here
...
in ...
...
in variable if variable
puts variable
else
puts "Nil"
end
2.) Reverse match order
case method()
in ... # Some cases here
...
in ...
...
in nil
puts "Nil"
in variable # Catch all
puts variable
end
Is there something nicer?
How could this also be used? It would allow a nice way to do comparison and assignment against nil using the one-line pattern matching expression:
if method() => variable
...
end
(This question was inspired by a question on assignments in if statements)