From: furufuru@... (Ryo Furue) Date: 2001-11-24T16:38:28+09:00 Subject: [ruby-talk:26298] Re: String#== : Why not error with different type? matz@ruby-lang.org (Yukihiro Matsumoto) wrote in message news:<1006526284.656538.15432.nullmailer@ev.netlab.jp>... > Hi, > > In message "[ruby-talk:25907] String#== : Why not error with different type?" > on 01/11/20, Ryo Furue writes: > > |I think it would be nice if String#== raised error if the argument > |isn't a String. > > No. It makes something harder in dynamic typed languages like Ruby. > For example, where ary is a non homogeneous array. > > ary.select{|x| x == "foo"} > > should be protected like > > ary.select{|x| begin x == "foo" rescue TypeError; false; end} Your point taken. However, it's different from my point, I'm afraid. In my opnion, if you really want a 'false' when the type of the argument is different, you should explicitly say so (as somebody pointed out in this thread): ary.select{|x| x.eql?("foo")} and I wish we left '==' to compare values only. Of course, you could argue that if we really want to compare values only, we should explicitly say so: ary.select{|x| (x <=> "foo") == 0} Then, the problem is: What is the most "natural" (intuitive) definition of '==' ? I'd like to argue that most programmers think (or "feel") they are comparing "values" in their mindset when they say '=='; they don't (usually) think they are comparing values *and* types. So, if you really need to mean the less common thing, you should use the less usual operator 'eql?', and you should leave the more common '==' for value comparisons only. And I think this (what I think is) more natural definition would be less error-prone, as I described in the original post. The operator =='s silently returning false for a different type can cause a subtle bug. When you write ary.select{|x| x == "foo"} the reader of your code will wonder: "Does the author of the code really mean that ary can be heterogeneous and s/he doesn't want to 'select' non-String component? Or does s/he mean that ary should be homogeneous and want to select only "foo"s?" When you use a heterogeneous array, you must be more careful than with a homogeneous one. A heterogeneous array is inherently more complex than a homogenous one, and can be more confusing. So, *I* would make my intention clearer by using 'eql?' instead of '=='. By the way, the pickaxe book's table 7.1 (p.81) *seems* to contradict actual definitions: Operator Meaning == Test for equal value. .... eql? True if the receiver and argument have both the same type and equal values. 1==1.0 returns true, but 1.eql?(1.0) is false. In fact, this doesn't contradict anything: it doesn't say what happens if == is given an argument of a different type. But, this *seems* to support my argument (that is, use eql? when you want to compare values and types; use == when you want to compare values). Thank you for your response, Ryo