简体   繁体   English

记住gets.chomp

[英]Memorize gets.chomp

I'm trying to make a text editor in Ruby, but I don't know how to memorize an input with gets.chomp . 我正在尝试在Ruby中创建文本编辑器,但是我不知道如何使用gets.chomp记住输入。

Here is my code so far: 到目前为止,这是我的代码:

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

while true
    tor
end

Ordinary variables , like outp , in a method are only visible (AKA have scope) inside that method. 方法中的普通变量(例如outp仅在该方法内部可见(AKA具有作用域)。

a = "aaa"
def x
  puts a
end
x # =>error: undefined local variable or method `a' for main:Object

Why is that? 这是为什么? For one thing, if you are writing a method and you need a counter, you can use a variable named i (or whatever) without worrying about other variables named i outside your method. 一方面,如果您正在编写一个方法并且需要一个计数器,则可以使用名为i的变量(或其他任何变量),而不必担心方法之外的其他名为i变量。

But... you want to interact with an outside variable in your method! 但是...您想与方法中的外部变量进行交互! This is one way: 这是一种方法:

@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

The @ gives this variable a greater visisbility (scope). @使此变量具有更大的可见性(范围)。

This is another way: pass the variable as an argument. 这是另一种方式:将变量作为参数传递。 It is as saying to your method: "Here, work with this.". 就像对您的方法所说:“在这里,使用它。”

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