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

前端 未结 3 1547
轻奢々
轻奢々 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
    

提交回复
热议问题