我正在尝试用Ruby语言做一个文本编辑器,但是我不知道如何用gets.chomp来记忆输入。
到目前为止,我的代码如下:
outp =
def tor
text = gets.chomp
outp = "#{outp}" += "#{text}"
puts outp
end
while true
tor
end发布于 2013-01-07 07:39:59
方法中的普通变量,如outp,仅在该方法中可见(也称为作用域)。
a = "aaa"
def x
puts a
end
x # =>error: undefined local variable or method `a' for main:Object为什么会这样呢?首先,如果您正在编写一个方法,并且需要一个计数器,那么您可以使用一个名为i (或其他任何名称)的变量,而不必担心方法之外的其他名为i的变量。
但是..。你想在你的方法中与外部变量交互!这是一种方法:
@outp = "" # note the "", initializing @output to an empty string.
def tor
text = gets.chomp
@outp = @outp + text #not "#{@output}"+"#{text}", come on.
puts @outp
end
while true
tor
end@赋予此变量更大的可见性(范围)。
这是另一种方式:将变量作为参数传递。这就像对你的方法说的那样:“这里,使用这个。”
output = ""
def tor(old_text)
old_text + gets.chomp
end
loop do #just another way of saying 'while true'
output = tor(output)
puts output
endhttps://stackoverflow.com/questions/14187210
复制相似问题