Forum: Ruby Overload [] operator and use a block ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8987d77750701f93bb78228c86d2c205?d=identicon&s=25 Stéphane Wirtel (Guest)
on 2007-02-28 21:22
(Received via mailing list)
Hi all,

I would like to know if it's possible to overload the [] operator to
use a block with it.

example:

class Test
   def []( x )
       # to do something here
       yield if block_given?
   end
end

t = Test.new
t['string'] do
    puts 'this is a test'
end

Thanks
83ca41657a99b65d99889abe712ba5e2?d=identicon&s=25 Jason Roelofs (Guest)
on 2007-02-28 21:34
(Received via mailing list)
Did you try to and find an error?

Jason
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-02-28 21:35
(Received via mailing list)
On 28.02.2007 21:15, Stéphane Wirtel wrote:
> end
>
> t = Test.new
> t['string'] do
>     puts 'this is a test'
> end

AFAIK it's not because the syntax does not allow a block with []:

irb(main):001:0> o=Object.new
=> #<Object:0x7ff96dc8>
irb(main):002:0> def o.[](x)
irb(main):003:1> yield x
irb(main):004:1> end
=> nil
irb(main):005:0> o[1] {|*a| p a}
SyntaxError: compile error
(irb):5: parse error, unexpected '{', expecting $
o[1] {|*a| p a}
       ^
         from (irb):5
         from :0

Kind regards

  robert
E7559e558ececa67c40f452483b9ac8c?d=identicon&s=25 Gary Wright (Guest)
on 2007-02-28 21:36
(Received via mailing list)
On Feb 28, 2007, at 3:21 PM, Stéphane Wirtel wrote:
> end
Not in Ruby 1.8.x but your example works just fine in Ruby 1.9.

The problem isn't with the definition of the method but in the
way the 1.8.x parser deals with the trailing block on the method
call.  The parser has been changed to recognize the block in 1.9.

Gary Wright
E34b5cae57e0dd170114dba444e37852?d=identicon&s=25 Logan Capaldo (Guest)
on 2007-02-28 21:39
(Received via mailing list)
On 2/28/07, Robert Klemme <shortcutter@googlemail.com> wrote:
> >        yield if block_given?
> irb(main):001:0> o=Object.new
>          from (irb):5
>          from :0
>
> Kind regards
>
>         robert


Yep.

You can however do
t.send(:[], 'string') do
   puts "This kind of defeats the purpose"
end
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (Guest)
on 2007-02-28 22:01
(Received via mailing list)
On Thu, Mar 01, 2007 at 05:38:14AM +0900, Logan Capaldo wrote:
> You can however do
> t.send(:[], 'string') do
>   puts "This kind of defeats the purpose"
> end

Or:

t.[]('string') { puts 'almost as bad' }
8987d77750701f93bb78228c86d2c205?d=identicon&s=25 Stéphane Wirtel (Guest)
on 2007-02-28 22:30
(Received via mailing list)
thanks Gary

Stephane Wirtel
This topic is locked and can not be replied to.