Feature #16137
closedAdd === to UnboundMethod
Description
Abstract¶
UnboundMethod class should have === so that it can be used in case statement.
Background¶
Method class has === method so that we can do something like:
require 'prime'
case 11
when Prime.method(:prime?) then :prime
end
However, we cannot do something like this:
positive = Integer.instance_method(:positive?)
case 11
when positive then :positive
end
Proposal¶
Add === method to UnboundMethod class.
Implementation¶
Minimal implementation in Ruby could be:
class UnboundMethod
def ===(other)
bind(other).call
end
end
Summary¶
=== for UnboundMethod can improve readability in case statement.
Updated by osyo (manga osyo) about 6 years ago
hi.
How about making # bind_call an alias of# ===?
class UnboundMethod
alias_method :===, :bind_call
end
see: https://bugs.ruby-lang.org/issues/15955#note-10
Also, you should consider the difference between when Integer.instance_method(:positive?) or when: positive?.to_proc.
case 11
when :positive?.to_proc then :positive
end
or
case 11
when Integer.instance_method(:positive?) then :positive
end
Thank you :)
Updated by shevegen (Robert A. Heiler) about 6 years ago
Since I love case/when statements in ruby, and I also like the idea to decouple methods
at "runtime", I agree with okuramasafumi.
I can not add much to potential use cases or what osyo asked, but personally I just like
the idea. :)
Updated by nobu (Nobuyoshi Nakada) about 6 years ago
As UnboundMethod#bind_call raises a TypeError unless the argument class matches, it isn't for when.
And the example doesn't look more readable to me.
Updated by Eregon (Benoit Daloze) about 6 years ago
With the new pattern matching:
case 11
in n if n.positive?
p :positive
end
Isn't that more readable and general?
Updated by okuramasafumi (Masafumi OKURA) almost 2 years ago
Now that we have had pattern match for a while, I agree with Eregon, we can utilize it more rather than adding new methods.
I cannot change its status so I hope someone will do so instead of me.
Updated by byroot (Jean Boussier) almost 2 years ago
- Status changed from Open to Closed