undefine instance var & [] (three questions)

F

Frantisek Psotka

Hi.

Iam not very deep in ruby. Please answer:

1) is the attr (method) slower than instance_variable_get/set ?
2) How can I define [] for instance_var_get/set (like in struct) ?
3) Is there a way to undefine @variable. I assign nil to them, but in
to_yaml output they are still there (even if empty). Is there way to
undefine them?

Thanks. FP.
 
S

Stefan Lang

2008/3/12 said:
Hi.

Iam not very deep in ruby. Please answer:

1) is the attr (method) slower than instance_variable_get/set ?

They serve different purposes. attr defines accessor methods
and the other allows access to instance variables via computed
variable names. So I'm not exactly sure what the purpose of the
speed comparison is.

Well, a let's benchmark anyway:
require "benchmark"
class Foo
attr :a, true
def initialize
@a = :a
end
end => nil
f = Foo.new
=> # said:
Benchmark.bm { |x| x.report { 1_000_000.times { f.a } } }
user system total real
0.560000 0.090000 0.650000 ( 0.656214)
=> true
Benchmark.bm { |x| x.report { 1_000_000.times {
f.instance_variable_get :mad:a } } }
user system total real
0.590000 0.100000 0.690000 ( 0.705093)
=> true
Benchmark.bm { |x| x.report { 1_000_000.times { f.a = 1 } } }
user system total real
0.590000 0.090000 0.680000 ( 0.698388)
=> true
Benchmark.bm { |x| x.report { 1_000_000.times {
f.instance_variable_set :mad:a, 1 } } }
user system total real
0.650000 0.090000 0.740000 ( 0.759085)
=> true

Conclusion: The differences are noise.
2) How can I define [] for instance_var_get/set (like in struct) ?

class Foo
def [](attr_name)
instance_variable_get :"@#{attr_name}"
end
def []=(attr_name, value)
instance_variable_set :"@#{attr_name}", value
end
end

Though using [] and []= will definitely be slower than using
classic accessor methods because we have to construct
the instance variable name for every access.
3) Is there a way to undefine @variable. I assign nil to them, but in
to_yaml output they are still there (even if empty). Is there way to
undefine them?

"ri instance_variable" reveals Object#remove_instance_variable.

Stefan
 
T

Thomas Wieczorek

"ri instance_variable" reveals Object#remove_instance_variable.

I found it there and tried a bit in irb:

class Foo
attr :bar
def initialize
@bar = "Baba"
end
end

foo = Foo.new #=> #<Foo:0x2ae813c @bar="Baba">
foo.instance_eval {remove_instance_variable :mad:bar } #=> "Baba"
foo #=> #<Foo:0x2ae813c> @bar is removed
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top