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

前端 未结 3 1545
轻奢々
轻奢々 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: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
    => #
    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 #
    

提交回复
热议问题