Key Highlights
A quick summary of the core Ruby syntax used in our code examples.
We'll cover the following...
Print out
Press + to interact
# print out textputs "a" + "b"; # => "ab"puts 1 + 2; # => 3puts "1" + "2"; # => "12"# print out without new line afterprint "Hi"print "Bob"# the screen output will be "HiBob"# print out joined multiple stringsprint "Bye", " John" # => "Bye John"
Variable assignment
Press + to interact
total = 1 + 2 + 3; # => total has value: 6average = total / 3;puts average; # => 2## print string with variableputs "total is " + total.to_sputs "average is #{average}"
Read user input
puts "type 'Hi'" input = gets # => type "Hi" puts input # => "Hi\n" ## normally strip off the new line "\n" input = gets.chomp # => "Hi" ## read an integer print "Enter a number" num = gets.chomp.to_i
Getting input from user and converting it to an integer
Conditional
Two boolean values—true
and false
Use of if
Press + to interact
score = -70if score < 0puts score = 0 # no negative scoreend
Use of unless
Press + to interact
score = -70unless score >= 0puts score = 0 # no negative scoreend