10.times{ |i| print("=")}
puts("binding")
class Demo
def initialize(n)
@secret = n
end
def get_binding
return binding()
end
end
k1 = Demo.new(99)
b1 = k1.get_binding
k2 = Demo.new(-3)
b2 = k2.get_binding
p eval("@secret", b1)
p eval("@secret", b2)
p eval("@secret")
class MyClass
@@x = " x"
def initialize(s)
@mystr = s
end
def getBinding
return binding()
end
end
class MyOtherClass
@@x = " y"
def initialize(s)
@mystr = s
end
def getBinding
return binding()
end
end
@mystr = self.inspect
@@xx = " some other value"
ob1 = MyClass.new("ob1 string")
ob2 = MyClass.new("ob2 string")
ob3 = MyOtherClass.new("ob3 string")
puts(eval("@mystr << @@x", ob1.getBinding))
puts(eval("@mystr << @@x", ob2.getBinding))
puts(eval("@mystr << @@x", ob3.getBinding))
puts(eval("@mystr << @@xx", binding))
10.times{ |i| print("=")}
puts("using send to call method")
name = "Fred"
puts( name.send( :reverse ) )
puts( name.send( :upcase ) )
10.times{ |i| print("=")}
puts("using send to create method")
class X
def a
puts("method a")
end
def addMethod( m, &block )
self.class.send( :define_method, m , &block )
end
end
ob = X.new
ob.instance_variable_set("@aname", "Bert")
ob.addMethod( :xyz ) { puts("My name is #{@aname}") }
ob.xyz
ob.freeze
ob.addMethod( :abc ) { puts("abc My name is #{@aname}") }
ob.abc
10.times{ |i| print("=")}
puts("remove method")
puts( "hello".reverse )
class String
remove_method( :reverse )
end
10.times{ |i| print("=")}
puts("undef_method method")
class Y
def somemethod
puts("Y's somemethod")
end
end
class Z < Y
def somemethod
puts("Z's somemethod")
end
end
zob = Z.new
zob.somemethod
class Z
undef_method( :somemethod )
end
10.times{ |i| print("=")}
puts("freeze object")
s = "Hello"
s << " world"
p s
s.freeze
if !(s.frozen?) then
s << " !!!";
end
10.times{ |i| print("=")}
puts("create class dynamicly")
puts("What shall we call this class? ")
className = gets.strip().capitalize()
Object.const_set(className,Class.new)
puts("I'll give it a method called 'myname'" )
className = Object.const_get(className)
className::module_eval{ define_method(:myname){
puts("The name of my class is '#{self.class}'" ) }
}
x = className.new
x.myname