From: Pat Maddox Date: 2006-05-09T06:24:51+09:00 Subject: Re: Question about instance_eval On 5/8/06, Pat Maddox wrote: > On 5/8/06, James Edward Gray II wrote: > > On May 8, 2006, at 3:30 PM, Pat Maddox wrote: > > > > > t.instance_eval { foo = 'foo' } > > > > Ruby will always see the above as a local variable declaration. > > There is no way around that. > > > > > I also know that t.instance_eval { @foo => 'foo' } would work in this > > > case. However, I'm trying to set a Rails attribute, so I have to go > > > through the method accessor. > > > > You've showed one way to handle it. Another is the use > > write_attribute(), if we are talking about ActiveRecord. > > > > James Edward Gray II > > > > > > Can I call pass in an object to instance_eval? Let me show you the > full class... > > > class ScenarioGenerator > def initialize > @rules = [] > end > > def add_rule(&r) > @rules << r > end > > def generate > s = Scenario.new > num_players = 0 > @rules.each do |r| > r.call(s) > end > > s.create_players(num_players) if num_players > 0 > s > end > end > > The reason I went to r.call(s) is so that I can do > g = ScenarioGenerator.new > g.add_rule { |s| s.sb = 200 } > > s then becomes the Scenario that I created. > > However I want to be able to modify num_players with a rule, so I need > instance_eval. I still need to be able to pass in the Scenario object > though. How could I do that? > > Pat > > Apparently I can't do that, so I changed the design up a bit so that I could do {|s| s.num_opponents = 3}. Thanks for the help James and Justin, I really appreciate it. Pat