Skip to content

Instantly share code, notes, and snippets.

@d12
Created October 21, 2019 15:28
Show Gist options
  • Save d12/6c4a738c4929c9bd4505fb17829a4330 to your computer and use it in GitHub Desktop.
Save d12/6c4a738c4929c9bd4505fb17829a4330 to your computer and use it in GitHub Desktop.
Ruby I/O

These are some notes that will help with the Repl.it assignment.

Input/Output

Getting input

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.

Output

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.

Putting them together

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.

Integers

In Ruby, integers are whole numbers, negative and positive. Strings must be converted to Integer types before arithmatic may be performed.

Type conversion

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.

Arithmatic

# 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

Conditionals

If statements

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment