Undefine instance var & [] (three questions)

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.

2008/3/12, Frantisek P. [email protected]:

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
=> #<Foo:0xb7adeb18 @a=:a>
> 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 :@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 :@a, 1 } } }
user system total real
0.650000 0.090000 0.740000 ( 0.759085)
=> true

Conclusion: The differences are noise.

  1. 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.

  1. 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

On Wed, Mar 12, 2008 at 12:11 PM, Stefan L.
[email protected] wrote:

  1. 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.

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 :@bar } #=> “Baba”
foo #=> #Foo:0x2ae813c @bar is removed