require ‘forwardable’
class MyQueue
extend Forwardable
attr_reader :queue
def initialize
@queue = []
end
def_delegator :@queue, :push, :mypush
end
q = MyQueue.new
q.instance_delegate [:clear, :first] => @q
#<main>': undefined methodinstance_delegate’ for #<MyQueue:0x2119e48
@queue=[]> (NoMethodError)
q.delegate [:clear, :first] => @q
#<main>': undefined methoddelegate’ for #<MyQueue:0x2109e40
@queue=[]> (NoMethodError)
Can you tell me what wrong I did? How to fix that?
Can anyone help me in this post?
Thanks
What are you trying to do exactly? If you want to add a couple of
delegations to an instance of MyQueue then maybe this is what you want
to do:
… your class definition
def exercise(obj)
puts “exercising #{obj}”
puts obj.first
obj.mypush ‘foo’
puts obj.first
obj.clear
puts obj.first
end
q1 = MyQueue.new
class << q1
delegate [:clear, :first] => :@queue
end
q2 = MyQueue.new
exercise q1 # should have first & clear methods delegated
exercise q2 # should complain at the first call of first
Hope this helps,
Mike
On 2013-04-07, at 2:50 AM, Love U Ruby [email protected] wrote:
q.delegate [:clear, :first] => @q
#<main>': undefined method delegate’ for #<MyQueue:0x2109e40
@queue=[]> (NoMethodError)
Can you tell me what wrong I did? How to fix that?
–
Posted via http://www.ruby-forum.com/.
–
Mike S. [email protected]
http://www.stok.ca/~mike/
The “`Stok’ disclaimers” apply.
Mike S. wrote in post #1105046:
q1 = MyQueue.new
class << q1
delegate [:clear, :first] => :@queue
end
Okay! So you defined it in the singleton class of q1. Why we need to
define it in the singleton class? BTW who is the caller of the method
delegate?
Thanks