7stud2
(7stud --)
7 April 2013 06:50
1
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 method `instance_delegate' for #<MyQueue:0x2119e48
@queue=[]> (NoMethodError)
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/ .
7stud2
(7stud --)
9 April 2013 08:35
2
Can anyone help me in this post?
Thanks
···
--
Posted via http://www.ruby-forum.com/ .
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 <lists@ruby-forum.com > wrote:
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 method `instance_delegate' for #<MyQueue:0x2119e48
@queue=[]> (NoMethodError)
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 Stok <mike@stok.ca >
http://www.stok.ca/~mike/
The "`Stok' disclaimers" apply.
7stud2
(7stud --)
9 April 2013 13:57
4
Mike Stok 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
···
--
Posted via http://www.ruby-forum.com/ .