Overload [] operator and use a block ?

S

Stéphane Wirtel

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
 
R

Robert Klemme

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

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
 
G

Gary Wright

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

t =3D Test.new
t['string'] do
puts 'this is a test'
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top