Variables, puts and gets Exercise
In case you get stuck anywhere, don't be afraid to ask the coaches! They are here to help and will gladly explain everything to you!
Take notes during the exercises. Even if you never look at them again, they will help you memorise things!
For these exercises, you will use your editor (Visual Studio Code or similar).
First, create an empty file with a meaningful name for this exercise, for example
variables.rb. Note the file extension
.rb! Also remember what folder you saved your file in. It makes sense to create a folder for each lesson of the course.
cd in the command line to change to that folder. When you run
ls you should see your file there.
Now you can run your Ruby program with
ruby variables.rb in the command line.
Repeat the above steps and remember to save your file in the editor before running it!
Hint 1: To output the value of something on screen, use
puts, for example
puts "Hello World!". Of course you can also use
puts with variables!
Hint 2: To allow the user to enter something in your program, use
gets. For example
my_input = gets.chomp will wait for the user to input something on the keyboard, followed by the return key. It will then save the text the user entered in the variable called
Let's write an interactive program. Here's what it should do: we want to provide a Fahrenheit to Celsius temperature converter. This is an example how the program flow could be:
Example interaction (user entered text is bold):
Thank you for your interest in the metric system. Please enter a temperature in Fahrenheit: 100 You entered 100.0° F, let me convert that for you... It's 37.77777777777778° C. Goodbye!
- Write a similar program that converts the other way around (°C to °F).