Feature #8053

Make coercion if #=== operator doesn't know what to do

Added by Ilya Vorontsov about 1 year ago. Updated 11 months ago.

[ruby-core:53245]
Status:Rejected
Priority:Normal
Assignee:Yukihiro Matsumoto
Category:core
Target version:next minor

Description

Related to http://bugs.ruby-lang.org/issues/7604
It'd be fine if === will do coerce when it doesn't know what to do. In ticket above I gave use-case for case-statement which needs that any ruby object could be coerced to a "pattern".
For example

case arr.end_with?
when ['several', 'words'] then puts 'arr have last two elements: several, words'
when ['word'] then puts 'arr have last element: word'
else puts 'cannot understand'
end

It'd be possible if Array#===(predicate) will simply use usual coerce call: predicate.coerce(arr) -- Predicate#coerce is a good point to understand behavior of such matching.

Another example:

class FalseYielder
def ===(other)
false
end
end
class MyString
def initalize(string); @string = string; end
attrreader :string
def coerce(other)
if other.is
a? Regexp
[other, self.string]
else
[FalseYielder.new, self]
end
end
end

case MyString.new('abcpatdef')
when /pat/ then 'it works'
end

Here we shouldn't monkeypatch Regexp class and it's good, we can make an error only in our own class MyString.

History

#1 Updated by Zachary Scott 11 months ago

  • Category set to core
  • Status changed from Open to Assigned
  • Assignee set to Yukihiro Matsumoto
  • Target version set to next minor

#2 Updated by Yukihiro Matsumoto 11 months ago

  • Status changed from Assigned to Rejected

Objects except for numbers does not have coerce protocol. I am not sure how far OP wants to dig in.
Design and implement coerce protocol? Or special kind of coercion for case statement?
In that sense, this proposal is half-baked.

Re-submit if you come up with concrete behavior definition, e.g. what "doesn't know" mean.

Matz.

#3 Updated by Boris Stitnicky 11 months ago

Sorry, Ilya, I already did some thinking, but didn't finish that flex-coerce yet.

Also available in: Atom PDF