Rubyでテキストエディタを作ろうとしているのですが、入力を記憶する方法がわかりませんgets.chomp
。
これまでの私のコードは次のとおりです。
outp =
def tor
text = gets.chomp
outp = "#{outp}" += "#{text}"
puts outp
end
while true
tor
end
メソッド内ののような通常の変数は、outp
そのメソッド内でのみ表示されます(別名スコープがあります)。
a = "aaa"
def x
puts a
end
x # =>error: undefined local variable or method `a' for main:Object
何故ですか?1つには、メソッドを作成していてカウンターが必要な場合は、メソッドの外部でi
名前が付けられた他の変数を気にせずに、名前が付けられた変数(またはその他)を使用できます。i
しかし...あなたはあなたのメソッドの外部変数と相互作用したいです!これは1つの方法です。
@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