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

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

提交回复
热议问题