Rails 和类变量 [英] Rails and class variables

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

问题描述

class MainController < ApplicationController

  @my_var = 123
   def index
    var1 = @my_var
   end

   def index2
    var2 = @my_var
   end
end

为什么 var1var2 都不等于 123?

Why is neither var1 no var2 equal to 123?

推荐答案

带有 @ 的变量是 ruby​​ 中的实例变量.如果您要查找类变量,它们的前缀为 @@,因此您应该使用 @@my_var = 123 代替.

Variables with @ are instance variables in ruby. If you're looking for class variables, they're prefixed with @@, so you should be using @@my_var = 123 instead.

您不能以这种方式使用实例变量的原因是,如果您在方法之外定义实例变量,它们与您的方法不在同一范围内,而仅在您的类被解释时有效.

And the reason you can't use instance variables that way, is because if you define instance variables outside methods, they don't live in the same scope as your methods, but only live while your class is interpreted.

var1 在你的例子中是一个局部变量,它只会在 index 方法内可见.

var1 in your example is a local variable, which will only be visible inside the index method.

示例:

class Foo
  @@class_variable = "I'm a class variable"

  def initialize
    @instance_variable = "I'm an instance variable in a Foo class"
    local_variable = "I won't be visible outside this method"
  end

  def instance_method_returning_an_instance_variable
    @instance_variable
  end

  def instance_method_returning_a_class_variable
    @@class_variable
  end

  def self.class_method_returning_an_instance_variable
    @instance_variable
  end

  def self.class_method_returning_a_class_variable
    @@class_variable
  end
end

Foo.new
=> #<Foo:0x007fc365f1d8c8 @instance_variable="I'm an instance variable in a Foo class">
Foo.new.instance_method_returning_an_instance_variable
=> "I'm an instance variable in a Foo class"
Foo.new.instance_method_returning_a_class_variable
=> "I'm a class variable"
Foo.class_method_returning_an_instance_variable
=> nil
Foo.class_method_returning_a_class_variable
=> "I'm a class variable"

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

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