我是Rails和ruby的新手。我正在研究类和实例变量的概念。我了解其中的区别,但是当我尝试在导轨中使用控制器时,我感到困惑。我所做的是在类方法之外声明了一个类和实例变量:
class BooksController < ApplicationController
# GET /books
# GET /books.json
@@world = "Hello World"
@insworld = "my hobby"
def index
@books = Book.all
binding.pry
respond_to do |format|
format.html # index.html.erb
format.json { render json: @books }
end
end
end
我的印象是@insworld的值是“我的爱好”,但是当我尝试查看@insworld的值时index method
,@ insworld返回的值为nil。@@ world具有“ Hello World”的值。那这里怎么了 他们不是在同一个类中定义的吗?
类也是Ruby中的对象,因此它们可以具有自己的实例变量,这些实例变量称为类实例变量。
@@world
是一个类变量@insworld
是一个类实例变量#index
是一个实例方法当您尝试访问@insworld
时#index
,Ruby会在A
对象(即A.new
)中搜索实例变量,因为这#index
是一个实例方法。
但是您将其定义@insworld
为类实例变量,这意味着它是在类对象本身中定义的(表示A
)。
以下代码演示:
class Hi
@@a = 1 # class variable
@b = 2 # class instance variable
def initialize
@c = 3 # instance variable
end
def test # instance method, works on objects of class Hi
puts @@a # => 1
puts @b # => nil, there is no instance variable @b
puts @c # => 3 # we defined this instance variable in the initializer
end
end
Hi.class_variables # => @@a
Hi.instance_variables # => @b
Hi.new.instance_variables # => @c
# Hi is an object of class Class
# Hi.new is an object of class Hi
请记住,所有实例变量nil
如果不存在则返回。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句