Please help gets is memorized as a word, and not input

Hi, I am new to Ruby, and I am trying to create a simple program that create batches file.
But I need help, because when I try the software, the gets that is used as input, it’s memorized i don’t know why as a word, like “scelta = gets” and scelta, that is the variable, it’s memorized like as gets is a word. Here is the code of my software
system “color 09”
puts “Eseguendo BatchMaker… by Sapphire Team”
system “timeout 3 > nul”
puts “Esistono 3 comandi, il comando ‘pcdown’, che può essere impiegato per la realizzazione”
puts “di file batch che appena aperti spengono il proprio computer; il comando ‘ripcomputer’, che”
puts “viene usato per la creazione di file batch che danneggiano un pc permanentemente, e ‘simplemalware’, che”
puts “crea un virus semplice, che se non contrastato subito può causare molti problemi.”
puts "Scelta: "
scelta = gets
if scelta == “pcdown”
File.open(‘pcdown.bat’, ‘w’) do |pcdown|
pcdown.puts “shutdown -p”
end
else
puts “ciao”
end

I am italian, so the words in the puts are italian

I’m not sure I understand your explanation of the error you’re getting, but I suspect that you are going a little pazzo (if that’s the right word) because you are entering 'pcdown' into your machine and your file isn’t opening as you expect. I will explain why.

Have a look at this:

2.6.0 :003 > x = gets
abc
=> "abc\n" 
2.6.0 :004 > x == 'abc'
=> false

(I’m using irb here.) The point is that gets preserves the \n new line character. With these lines in your code:

scelta = gets
if scelta == “pcdown”
  # File.open, etc.
end

You are never going to execute your File.open, because when you enter pcdown into your program, scelta will equal "pcdown\n" rather than `“pcdown”.

The fix is simple: just apply the chomp method to the result. Like this:

scelta = gets.chomp

That will remove the newline character from the string, and should solve your problem.

As a general rule, you should use gets.chomp rather than gets unless you know that you want to preserve the newline character for some reason.

I tried as you said, and it worked, thank you very much.

Of course. That little detail trips up a lot of people who are new to Ruby! (Myself included.)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs