繁体   English   中英

记住gets.chomp

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM