
Open your text editor. Any text editor. Type the following line and save it as chunky.rb:
print "Chunky bacon!"
Now open your terminal and run it:
$ ruby chunky.rb
Chunky bacon!
There. Chunky bacon. Your first Ruby program. The only thing that line does is print a string to the screen. But that’s not nothing. That’s everything.
Numbers
5 # an integer 3.14 # a floating point number 2_000_000 # underscores make large numbers readable
In Ruby, everything is an object. Even numbers. That means numbers have methods:
5.to_s # => "5" (converts to string)
5.times { puts "hello" } # prints "hello" five times
Strings
"hello, world" # double-quoted string
'single-quoted' # single-quoted — no interpolation
"chunky #{1 + 1}" # => "chunky 2" — interpolation with #{}
String interpolation with #{} is one of Ruby’s most useful features. Any Ruby expression inside #{} gets evaluated and inserted into the string.
Variables
name = "Trady Blix" age = 9 name # => "Trady Blix" age # => 9
Variables in Ruby start with a lowercase letter or underscore. You don’t declare types. The variable just takes on whatever value you assign.
String Methods
name = "trady blix"
name.upcase # => "TRADY BLIX"
name.length # => 10
name.reverse # => "xilb ydart"
name.include?("blix") # => true
name.split(" ") # => ["trady", "blix"]
name.capitalize # => "Trady blix"
Getting Input
print "What is your name? "
name = gets.chomp
puts "Hello, #{name}!"
gets reads a line of input from the user. chomp removes the trailing newline character that gets includes.
Conditionals
age = 9 if age > 10 puts "old enough" elsif age == 9 puts "exactly nine" else puts "younger" end
Ruby also has a one-line conditional form:
puts "hello" if name == "Trady Blix" puts "goodbye" unless name == "Trady Blix"