简体   繁体   中英

Instance variables in Ruby

Ruby 1.9

I suddenly realize I don't understand how to define and initialize an instance variable in Ruby. It must be used only within a certain class and not accessible out of a class at all, so attr_accessor or attr_reader is not what I need.

class MyClass

  #how do I initialize it?
  @my_var = 'some value'

  def method1
    #I need to do something with @my_var
    puts @my_var
  end
  def method2
    #I need to do something with @my_var
    puts @my_var
  end
end

a = MyClass.new
a.method1 #empty 
a.method2 #empty

So I found that there is another way to do it

class MyClass

  #is this the only way to do it?
  def initialize
    @my_var = 555
  end

  def method1
    #I need to do something with @my_var
    puts @my_var
  end

  def method2
    #I need to do something with @my_var
    puts @my_var
  end
end

a = MyClass.new
a.method1 #555; it's ok
a.method2 #555; it's ok

Well, is second approach the right one?

each class has an initialize() method that acts similar to a constructor in other languages, instance variables should be initialized there:

class MyClass

  def initialize
     @my_var = 'some value'
  end

  # etc...
end

Yes, initialize is the right way.

But you may also make:

class MyClass

  def method1
    #I need to do something with @my_var
    puts @my_var ||= 555
  end

  def method2=(x)
    #I need to do something with @my_var
    puts @my_var = x
  end
end

#Test:
x = MyClass.new
x.method1      #555
x.method2= 44  #44
x.method1      #44

When method1 is called the first time, it initialize the variable.

Edit: It does not work as expected, when you assign nil

x = MyClass.new
x.method1         #555
x.method2= nil   #nil
x.method1          #again 555

This version works better:

class MyClass

  def method1
    @my_var = 555 unless defined? @my_var
    puts @my_var 
  end

  def method2=(x)
    puts @my_var = x
  end
end

x = MyClass.new
x.method1         #555
x.method2= nil   #nil
x.method1          #keeps nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM