Feature #16137
closed
Added by okuramasafumi (Masafumi OKURA) about 5 years ago.
Updated 11 months ago.
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.
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 :)
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. :)
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.
With the new pattern matching:
case 11
in n if n.positive?
p :positive
end
Isn't that more readable and general?
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.
- Status changed from Open to Closed
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0