On Jan 21, 6:38 am, "Sun" <a... / hut.at> wrote:
> Thanks for your quick and prompt answer!
> got it.
>
> greetings,
> Sun
>
> "Robert Klemme" <shortcut... / googlemail.com> wrote in message
>
> news:9e3fd2c80801210246j2c4690d7i9f280cdb7ceef260 / mail.gmail.com...
>
> > 2008/1/21, Sun <a... / hut.at>:
> >> I came cross a ruby class with function defined as:
>
> >> class A
> >> ...other functions...
> >>  def [](var1)
> >>      ...
> >>      ....
> >>   end
> >> end
>
> >> I do not know what this function is for and how to use it. any tips?
>
> > It allows you to define the [] operator:
>
> > irb(main):001:0> class Foo
> > irb(main):002:1> def [](v) "foo<#{v}>" end
> > irb(main):003:1> end
> > => nil
> > irb(main):004:0> Foo.new[123]
> > => "foo<123>"
>
> > Typically this is used for index based lookups (like Array and Hash
> > do) but you are free to define your own semantic.  There is also the
> > assignment operator []= which can be defined in a similar way (but
> > with two arguments).
>
> > Kind regards
>
> > robert
>
> > --
> > use.inject do |as, often| as.you_can - without end

Out of curiosity... operator overloading and it's ilk are (by many)
considered to be bad things because it can make it hard to figure out
what's happening in the code, especially for dynamic languages where
they can change on the fly. The reason for this thought is, I believe,
because it can be difficult to understand what code is doing if the
definitions of "standard" operations are or where they come from.

Along those lines, is there a current way to ask Ruby where the
definition comes from for a given operator or, more generally, method?
Ie, Ruby needs to do a lookup to find out what definition to use. Is
there a way to ask it to do that lookup and report the results?

Thanks,
Rob Seeger