These are some notes that will help with the Repl.it assignment.
string = gets.chomp
This will stall the program waiting for the user to enter text. After the user has entered text and hit enter
, string
will be equal to the text the user typed in.
puts "Hello!"
This will print Hello!
to the screen.
Notice Hello!
is surrounded in "
in our code. This means Hello!
is a string, a type in Ruby that represents text.
puts "Please enter a word"
string = gets.chomp
puts string
This will ask the user for a word, then print the word that the user entered.
In Ruby, integers are whole numbers, negative and positive. Strings must be converted to Integer types before arithmatic may be performed.
string = "5"
int = string.to_i
string
is a String type, and arithmatic cannot be performed on strings. To perform arithmatic, we first need to convert it to an Integer with to_i
.
# This works as expected
sum = 5 + 5
# This does not work as expected
sum = "5" + "5"
# This also does not work as expected,
# since `number` is a string, not an integer.
number = gets.chomp
sum = 5 + number
Use if
statements to alter program flow based on a condition.
if 5 > 10
puts "5 is greater than 10!"
else
puts "5 is NOT greater than 10!"
end