Schüle Daniel said:
Hello all,
is it possible to delete a variable
for example
class X
def foo(k);@f=k;end
def bar; end # how to remove @f?
def f;@f;end
end
x=X.new
x.foo(1) # create @f
x.f => 1 # it's there
x.bar # delete it
x.f => # Error
is it possible?
and same question to local variables
Regards, Daniel
Not as far as I know. What do you need that for?
The usual approach is to set something to nil. If you need similar behavior
you can either use a hash and test for key presence or use OpenStruct -
although that won't raise an exception:
=> nil
Of course you can create your own class.
class ChangingFields
def method_missing(s,*a,&b)
case s.to_s
when /^(.*)=$/
field = $1
class << self;self;end.class_eval do
attr_accessor field
end
send(s,*a,&b)
else
super
end
end
def remove_field(field)
class << self;self;end.class_eval do
remove_method( field )
remove_method( "#{field}=" )
end
instance_variable_set("@#{field}", nil)
end
end
irb(main):052:0> c=ChangingFields.new
=> #<ChangingFields:0x101d0b88>
irb(main):053:0> c.foo = 1
=> 1
irb(main):054:0> c
=> #<ChangingFields:0x101d0b88 @foo=1>
irb(main):055:0> c.foo
=> 1
irb(main):056:0> c.remove_field :foo
=> nil
irb(main):057:0> c
=> #<ChangingFields:0x101d0b88 @foo=nil>
irb(main):058:0> c.foo
NoMethodError: undefined method `foo' for #<ChangingFields:0x101d0b88
@foo=nil>
from (irb):37:in `method_missing'
from (irb):58
from (null):0
Kind regards
robert