Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

ruby - Rails and class variables

class MainController < ApplicationController

  @my_var = 123
   def index
    var1 = @my_var
   end

   def index2
    var2 = @my_var
   end
end

Why is neither var1 no var2 equal to 123?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 in your example is a local variable, which will only be visible inside the index method.

Examples:

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...