中实例变量和局部变量的区别

中实例变量和局部变量的区别

本文介绍了Ruby : Ruby 中实例变量和局部变量的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Rails 和类变量

谁能告诉我 Ruby 实例变量和局部变量有什么区别?

Could anybody please tell me whats the difference between Ruby Instance variables and Local variables ?

据我所知,实例变量和局部变量都是相同的,并且都在方法本身内部声明,除了实例变量使用@符号表示.

As far as i know both Instance variables and Local variables are same , and both are declared inside the method itself and except that instance variables are denotated using @ symbol .

推荐答案

范围.局部变量仅在定义它的方法中可见/可用(即,它在方法返回时消失).

It's a matter of scope. A local variable is only visible/usable in the method in which it is defined (i.e., it goes away when the method returns).

另一方面,实例变量在定义它的类的实例中的任何其他地方都是可见的(这与类变量不同,类变量在类的所有实例之间共享).但是请记住,何时定义实例变量很重要.如果你在一个方法中定义了一个实例变量,但在调用第一个方法之前尝试在另一个方法中使用它,你的实例变量的值将为 nil:

An instance variable, on the other hand, is visible anywhere else in the instance of the class in which it has been defined (this is different from a class variable, which is shared between all instances of a class). Keep in mind, though, that when you define the instance variable is important. If you define an instance variable in one method, but try to use it in another method before calling the first one, your instance variable will have a value of nil:

def method_one
  @var = "a variable"

  puts @var
end

def method_two
  puts @var
end

@var 将有不同的值,具体取决于您调用每个方法的时间:

@var will have a different value depending on when you call each method:

method_two() # Prints nil, because @var has not had its value set yet

method_one() # Prints "a variable", because @var is assigned a value in method_one

method_two() # Prints "a variable" now, because we have already called method_one

这篇关于Ruby : Ruby 中实例变量和局部变量的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:35