简体   繁体   中英

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 .

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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