Normal Variables Vs Instance variable in Ruby, Whats the difference?

前端 未结 3 1546
轻奢々
轻奢々 2021-02-07 13:57

Consider the following sample ruby class

class User
  def hello
    puts \"hello\"
  end
end

now, for initialization. there are two ways

<
相关标签:
3条回答
  • 2021-02-07 14:08

    A local variable can be used only within the method in which it is defined (or, when the variable is defined at the top level, only outside of any method). An instance variable can be used from any method that is called on the same instance.

    Here's an example where you can see the difference:

    @tr = User.new
    
    def foo
      @tr.hello
    end
    
    foo
    # Hello World
    
    
    tr = User.new
    
    def bar
      tr.hello
    end
    
    bar
    # Exception because tr is not accessible from within bar
    
    0 讨论(0)
  • 2021-02-07 14:26

    A normal variable has scope only within the current context; an instance variable has scope throughout one instance of a class. In your case they're confused because the context is main, which acts as an instance of Object.

    Consider the following, which may make things clearer

    class User
      def set_name
        @name = "Bob"
        surname = "Cratchett"
      end
    
      def hi
        puts "Hello, " + @name
      end
    
      def hello
        puts "Hello, Mr " + surname
      end
    end
    
    irb(main):022:0> u = User.new
    => #<User:0x29cbfb0>
    irb(main):023:0> u.set_name
    irb(main):024:0> u.hi
    Hello, Bob
    => nil
    irb(main):025:0> u.hello
    NameError: undefined local variable or method `surname' for #<User:0x29cbfb0 @name="Bob">
    
    0 讨论(0)
  • 2021-02-07 14:31

    The normal variable is called a local variable and is local to the code construct in which it was defined (if you define it in a method it cannot be accessed outside that method).

    An instance variable is local to a specific instance of an object. If one object changes the value of the instance variable, the change only occurs for that object.

    There are also class variables local to all instances of the class:

    @@class_variable = 'a class variable'

    And global variables accessible from anywhere within the program:

    $global_variable = 'a global variable'

    0 讨论(0)
提交回复
热议问题