在Ruby中声明变量?
我何时知道何时声明变量而不是Ruby?
我想知道为什么第一个代码需要输入声明为字符串并且在块之外,而第二个块则不需要。
input = '' while input != 'bye' puts input input = gets.chomp end puts 'Come again soon!'
与:
while true input = gets.chomp puts input if input == 'bye' break end end puts 'Come again soon!'
Ruby中没有声明变量。 相反,规则是变量必须在使用之前出现在赋值中。
查看第一个示例中的前两行:
input = '' while input != 'bye'
while
条件使用变量input
。 因此,在此之前必须进行分配。 在第二个例子中:
while true input = gets.chomp puts input
同样,变量input
在puts
调用中使用之前被赋值。 在这两个例子中,一切都是对的。