From: "Peña, Botp" Date: 2007-08-23T16:45:22+09:00 Subject: Re: Changing "self" for cleaner code From: come [mailto:come.news@free.fr] # I ask that because I'm doing a program to access different unix os and # I would like to write something like : # with my_server do # ls("-lrt") # ps("-efl") # end is instance_eval ok for you? irb(main):013:0> system "qri instance_eval" --------------------------------------------------- Object#instance_eval obj.instance_eval(string [, filename [, lineno]] ) => obj obj.instance_eval {| | block } => obj ------------------------------------------------------------------------ Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj's instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors. class Klass def initialize @secret = 99 end end k = Klass.new k.instance_eval { @secret } #=> 99 => true some simple example, irb(main):014:0> def with x, &block irb(main):015:1> x.instance_eval &block irb(main):016:1> end => nil irb(main):017:0> with "test" do irb(main):018:1* p length irb(main):019:1> p upcase irb(main):020:1> p capitalize irb(main):021:1> p self irb(main):022:1> end 4 "TEST" "Test" "test" => nil irb(main):023:0> kind regards -botp