Reputation: 23
I followed an example for this to start learning Ruby. The following code works inside of my text editor (Visual Studio Code). But when I open the file using the interactive ruby program. It doesn't seem to work.
puts "Hello there! Please enter a number to square: "
number = gets.chomp.to_i
def squared(number)
squared = number * number
return squared.to_s
end
puts "Your number is: " + number.to_s
puts "Your number squared is: " + square(number)
It prints out the initial "Hello there! Please enter a number to square:" But once I type a number and press enter, the program abruptly closes.
Upvotes: 2
Views: 236
Reputation: 10546
The problem is that you're double-clicking the example.rb
file, which opens in cmd.exe
and then closes automatically when it is done executing example.rb
. That is the normal behavior for Windows: cmd.exe
closes automatically after running whatever application invoked it.
What you want to do instead is manually open a command prompt (cmd.exe
) and then run your application with ruby example.rb
. This will keep cmd.exe
open after your application finishes running, because cmd.exe
was not invoked by your application; it was invoked manually by you.
This will allow you to see the Your number is:
output after your application has finished running. This output is still being printed when you double-click example.rb
, but the window closes so quickly that you can't see it.
Additionally, your application has some errors in it. Specifically, you're attempting to call square(number)
when you should be calling squared(number)
.
Here is your code cleaned up a little bit:
puts 'Hello there! Please enter a number to square: '
number = gets.chomp.to_i
def squared(number)
number * number
end
puts "Your number is: #{number}"
puts "Your number squared is: #{squared(number)}"
Note the use of single quotes for strings that do not include string interpolation, the implicit return for the squared
method, and string interpolation for the puts
calls.
Upvotes: 1