How do I pass a block to the initialize method that calls some methods
of the new object? Here is what I want to get:
class Test
def initialize(foo)
…
end
def set=(myval)
@set=myval
end
def set @set
end
end
t=Test.new(“foo”){set=89}
puts t.set
=>89
You’re going to need to state the receiver explicitly for that call to
set (because otherwise Ruby will favor the interpretation that it’s a
local variable assignment). So, you might end up with something like:
class Test
attr_accessor :set # save some typing
def initialize(foo)
yield(self)
end
end
If you want to do something “from within” an object (Test) why not to create
a method in Test to do it. Or at lease a method to set var1, var3 and var54
altogether, as they are related anyway according to your code.
In Ruby you can call object’s methods from the block, that’s no problem,
even for initialize(). The problem you stepped onto is exactly the one I got
into quite recently, when trying to use “method=” where Ruby interprets it
as an assignment. Look for the recent thread “Method/Assignment ambiguity”
where David Black presented an excellent explanation of inevitable problems
were Ruby treating the case not the way it does now.
Gennady.
···
----- Original Message -----
From: “Peter Schrammel” peter.schrammel@gmx.de
Newsgroups: comp.lang.ruby
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Thursday, May 08, 2003 8:32 AM
Subject: Re: [Q] Block passing: obj.new(){block}