2013-01-06 24 views
0

我想在Ruby中創建文本編輯器,但我不知道如何使用gets.chomp記住輸入。記住gets.chomp

這是到目前爲止我的代碼:

outp = 
def tor 
    text = gets.chomp 
    outp = "#{outp}" += "#{text}" 
    puts outp 
end 

while true 
    tor 
end 
+1

你是什麼意思「記憶」? –

+1

你有什麼是無效的Ruby代碼。 –

+1

懷疑memoize? –

回答

0

普通變量,如outp,在方法纔可見(AKA具有範圍),該方法內。

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 
end 
+0

謝謝。那正是我正在尋找的 – TorB