[英]Memorize gets.chomp
我正在嘗試在Ruby中創建文本編輯器,但是我不知道如何使用gets.chomp
記住輸入。
到目前為止,這是我的代碼:
outp =
def tor
text = gets.chomp
outp = "#{outp}" += "#{text}"
puts outp
end
while true
tor
end
方法中的普通變量(例如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.