Search⌘ K
AI Features

Key Highlights

Learn the foundational elements of Ruby programming such as variable assignment, user input, conditionals including if and case statements, and looping constructs like while and for loops. Understand how to work with arrays, hashes, and methods to build interactive and structured Ruby programs.

Print out

Ruby 3.1.2
# print out text
puts "a" + "b"; # => "ab"
puts 1 + 2; # => 3
puts "1" + "2"; # => "12"
# print out without new line after
print "Hi"
print "Bob"
# the screen output will be "HiBob"
# print out joined multiple strings
print "Bye", " John" # => "Bye John"

Variable assignment

Ruby 3.1.2
total = 1 + 2 + 3; # => total has value: 6
average = total / 3;
puts average; # => 2
## print string with variable
puts "total is " + total.to_s
puts "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

Ruby 3.1.2
score = -70
if score < 0
puts score = 0 # no negative score
end

Use of unless

Ruby 3.1.2
score = -70
unless score >= 0
puts score = 0 # no negative score
end

Single line use of

...