在 Ruby 中声明变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16246794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:54:35  来源:igfitidea点击:

Declaring variables in Ruby?

ruby

提问by Alex Wilsen

When do I know when to declare a variable and not to in Ruby?

我什么时候知道什么时候声明一个变量而不是在 Ruby 中?

I would like to know why the first code needs input to be declared as a string and outside of the block, while the second block doesn't.

我想知道为什么第一个代码需要将输入声明为字符串并在块之外,而第二个块不需要。

input = ''
while input != 'bye'
  puts input
  input = gets.chomp
end
puts 'Come again soon!'

versus:

相对:

while true
  input = gets.chomp
  puts input 
  if input == 'bye'
    break 
  end
end
puts 'Come again soon!'

回答by Gene

No variable is ever declared in Ruby. Rather, the rule is that a variable must appear in an assignment before it is used.

Ruby 中从未声明过任何变量。相反,规则是变量在使用之前必须出现在赋值中。

Look at the first two lines in your first example:

查看第一个示例中的前两行:

input = ''
while input != 'bye'

The whilecondition uses the variable input. Therefore the assignment is necessary before it. In the second example:

while条件使用变量input。因此在它之前需要赋值。在第二个例子中:

while true
  input = gets.chomp
  puts input 

Again, the variable inputis assigned before it is used in the putscall. All is right with the world in both examples.

同样,变量inputputs调用中使用之前被赋值。在这两个例子中,世界一切都好。