Ruby Instance variables

ray · 2012年04月12日 · 最后由 ray 回复于 2012年04月14日 · 4057 次阅读

instance variable(实例变量),除了有个明显的特性是@符号在变量名之前外,还有一个是 spring into life the first time they are assigned to (第一次给它赋值的时候它才会存在)

class Hello
  def create_some_state
    @hello = "hello"
  end
end

h = Hello.new
p h.instance_variables 

h.create_some_state
p h.instance_variables #列出所有的实例变量

Output: [] ["@hello"]

你还可以用 initialize 方法来初始化实例变量

class Hello
  def initialize(val)
    @hello = val
  end
end

obj = Hello.new(1)
p obj.instance_variables


还有一种方法是用 Module 方法 attr_accessor (read/write), attr_writer(write), attr_reader (read)

class Hello
  attr_accessor :hello
end

h = Hello.new
p h.instance_variables 

h.hello = "hello"
p h.instance_variables

# Output
[]
["@hello"]

注意:实例变量还是没有生成,直到给它赋值。

原文: http://stackoverflow.com/questions/826734/when-do-ruby-instance-variables-get-set

实例变量就是普通变量,只不过加了一个@, 另外作用域不一样而已。普通变量你不赋值,直接用也是不行的呀。

#1 楼 @zw963 实例变量 应该是对象的属性。不算是普通变量吧。 不过的确普通变量不赋值也是不可以用的

class Hello
    @hello = "hello"
    def display
        puts @hello
    end
end

h = Hello.new
h.display  #nil

ruby 的 self 很恶心啊。

#2 楼 @ray

实例变量就是普通变量~ 只不过作用域是整个类,而不仅仅是一个方法。

属性跟实例变量有什么关系??

建立了 accessor 方法才是属性,没有方法怎么能叫做属性?

#3 楼 @zw963 嗯。学习了。我一直迷惑这个问题。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号