rails 控制器中的实例和类变量 [英] instance and class variables in rails controller

查看:54
本文介绍了rails 控制器中的实例和类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 和 ruby​​ 的新手.我正在研究类和实例变量的概念.我理解其中的区别,但是当我尝试使用 Rails 中的控制器时,它让我感到困惑.我所做的是在类方法之外声明了一个类和实例变量:

I'm new to rails and ruby. I was studying the concept of class and instance variables. I understood the difference but when I tried it out using the controller in rails it got me confused. What I did is I declared a class and instance variables outside the class methods:

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具有我的爱好"的价值,但是当我在index方法中尝试检查@insworld的值时,@insworld正在返回一个零值.@@world 的值为Hello World".那么这里发生了什么?它们不是定义在同一个类中吗?

I was under the impression that @insworld has the value of "my hobby", but when I tried to check the value of @insworld when I was inside the index method, @insworld was returning a nil value. @@world has the value of "Hello World". So what happened here? Aren't they defined in the same class?

推荐答案

类在 Ruby 中也是对象,因此它们可以拥有自己的实例变量,称为类实例变量.

Classes are also objects in Ruby, so they can have their own instance variables which are called class instance variables.

  • @@world 是一个类变量
  • @insworld 是一个类实例变量
  • #index 是一个实例方法
  • @@world is a class variable
  • @insworld is a class instance variable
  • #index is an instance method

当您尝试访问 #index 中的 @insworld 时,Ruby 会搜索 A 对象中的实例变量(意思是 A.new) 因为 #index 是一个实例方法.

When you try to access @insworld in #index, Ruby searches for the instance variable in the A object (meaning A.new) because #index is an instance method.

但是您将@insworld 定义为类实例变量,这意味着它是在类对象本身中定义的(即A).

But you defined @insworld as a class instance variable which means it is defined in the class object itself (meaning 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.

Keep in mind that all instance variables return nil if they don't exist.

这篇关于rails 控制器中的实例和类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆