From: Sun Date: 2008-01-21T20:39:56+09:00 Subject: Re: what does 'def [](var1)' means and how to use? Thanks for your quick and prompt answer! got it. greetings, Sun "Robert Klemme" wrote in message news:9e3fd2c80801210246j2c4690d7i9f280cdb7ceef260@mail.gmail.com... > 2008/1/21, Sun : >> 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 >