I think this is a philosophical ruby question.

Why does ruby allow fixnums to be accessed as hashes?

  5[:some_key]
  => 0

Not all types can be used this way:

  3.1415[:some_key]
  NoMethodError: undefined method '[]' for Float

  Array.new()[:some_key]
  TypeError: Symbol as array index

  etc.

And the perhaps larger question -- why would 5[:some_key] return *zero*,
when all other hash-y accesses to nonexistent keys (that I know of)
return *nil*?

Can be dangerous situations like:

  def f(options)
    # Only execute following if caller has called us with :do_bad_stuff => true
    if (options[:do_bad_stuff])   # <--- idiomatically common
      # watch out... Bad stuff here!
    end
  end

If options somehow were a Fixnum above (don't ask! :-) ), then
options[:do_bad_stuff] is 0, which is *not* false, and so the "if"
statement will inadvertently execute.

        -glenn

--~--~---------~--~----~------------~-------~--~----~
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
-~----------~----~----~----~------~----~------~--~---

Reply via email to