Is it possible to change the value of self just to enter the context
of an object, like for example in IRB ? For instance, is it possible
to write something like :
File.open(“file.txt”,“w”) do
puts “Hello World”
end
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>
Thanks for your anwser.
I knew I could write the form “File.open(…) do |x| … end”. I read
nearly all books on Ruby/Rails right now ;-). The last I’m reading is
“Practical Ruby for System Administration”, Apress. A good book, too.
I was surprised.
But I cant’t practice as often as I would, so I miss some automatism.
I was asking myself if i couldn’t write something like :
with my_object do something end
instead of :
with my_object do |o| o.something end
I found it would be a little bit cleaner to write like that. The first
answer gave me an answer : I can define “with” myself.