Updated: 23 December 2025

From the Ruby Documentation

Interactive Ruby

We can use irb to run an interactive Ruby shell, when open, it will look like this:

1
irb(main):001:0>

Once we’ve got that open, we can type a value, and the interactive shell will evaluate it

1
irb(main):001:0> "Hello World"
2
=> "Hello World"

Though, to formally print something we can use puts like so:

1
irb(main):002:0> puts "Hello World"
2
Hello World
3
=> nil

We can also see that the result of the puts command is nil which is the Ruby version of a nothing value

Math

We can do basic math using IRB as well, like so:

1
irb(main):004:0> 5*7
2
=> 35
3
irb(main):005:0> 5**7
4
=> 78125
5
irb(main):006:0> Math.sqrt(5)
6
=> 2.23606797749979
7
irb(main):007:0> Math.sin(0)
8
=> 0.0
9
irb(main):008:0> Math.acos(1)
10
=> 0.0

Methods

Defining a Method

We can define a method using def and end, so a method that prints Hello World would look like this:

1
def hi
2
puts "Hello World"
3
end

Or, in the shell

1
irb(main):017:0> def hi
2
irb(main):018:1> puts "Hello World"
3
irb(main):019:1> end
4
=> :hi

Calling a Method

We can then call a method using either the name of the method, or the name followed by () if the method has no inputs

1
irb(main):020:0> hi
2
Hello World
3
=> nil
4
irb(main):021:0> hi()
5
Hello World
6
=> nil

Method Parameters

We can define hi such that it takes a name parameter like so:

1
def hi(name)
2
puts "Hello #{name}"
3
end

Also note how string interpolation/templates can be done in the above string

1
irb(main):026:0> hi("bob")
2
Hello bob
3
=> nil

We can also call methods on an object, for example name by using either the method name with or without parenthesis as mentioned before

1
name.capitalize
1
name.capitalize()

We can then implement that in our hi method

1
def hi(name)
2
puts "Hello #{name.capitalize}"
3
end

Which can be called like:

1
hi("bob")

or

1
hi "bob"

Classes

Classes are defined using the class keyword

1
class Greeter
2
def initialize(name = "World")
3
@name = name
4
end
5
6
def say_hi()
7
puts "Hi #{@name}"
8
end
9
10
def say_bye()
11
puts "Hi #{@name}"
12
end
13
end

We can create an instance of the Greeter class by using Greeter.new, like so

1
greeter = Greeter.new("bob")

And we can then use it with:

1
irb(main):029:0> greeter.say_hi
2
Hi bob
3
=> nil
4
irb(main):030:0> greeter.say_bye
5
Hi bob
6
=> nil