Dave Thomas <Dave / PragmaticProgrammer.com> wrote:
>
>"David A. Black" <dblack / saturn.superlink.net> writes:
>
> > Also:
> >
> >    b = Foo.new("Hi")
> >    h[b] = 123
> >    h.each_key do |k| puts k.type end
> >      => String
> >         String
>
>Even worse
>
>    class Foo < String
>      def hash
>         super + 1
>      end
>    end
>
>    f = Foo.new("hello")
>
>    h = { f => "one", "hello" => "two" }
>
>    p h   #=>  "hello" => two
>
>I emailed Matz on this last night: I suspect we have a bug where
>subclasses of String get treated as if they were strings. When a
>string is used as a hash key, it is copied automatically, so that
>subsequent changes to the string don't affect the hash. I'm guessing
>that the Foo object is undergoing the same treatment, and therefore
>that Ruby can't tell the resulting copied key from the next "hello"
>that comes along.

Perhaps not such a basic question then. :-)

I was trying to reconcile the idea of hashing objects with
the useful behaviour of Perl and strings.  (Two different
instances of "Hello" are recognized as being one.)  So it
is quite useful that strings are not hashed as objects.
But it clashes with how hashes work otherwise.

Now here that clash is obvious because I have another class,
but if someone starts thinking of strings as objects:

  a = "hello"
  b = "hello"
  def a.meth
    puts "I am 'a' method"
  end

  h = {a => "a", b => "b"}
  puts h[a]
  puts h[b]
  a.meth
  b.meth

Now we have 2 instances of String which are clearly not
the same object, and are not being thought of as being
part of the same object, which are not distinguished in
a hash.

An incidental side-question.  Is it reliable that the
second time a key appears in the list out of which a hash
is constructed, wins?  I got bitten once in Perl by the
fact that it looked like that from an initial test, but
when I pushed it the behaviour wasn't actually reliable.
What I wanted it for was to produce hashes with defaults
specified like this:

  %foo = (%default, @_);

It worked well enough to pass simple tests and then
failed in production. :-(

Cheers,
Ben
_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com