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:
1irb(main):001:0>Once we’ve got that open, we can type a value, and the interactive shell will evaluate it
1irb(main):001:0> "Hello World"2=> "Hello World"Though, to formally print something we can use puts like so:
1irb(main):002:0> puts "Hello World"2Hello World3=> nilWe 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:
1irb(main):004:0> 5*72=> 353irb(main):005:0> 5**74=> 781255irb(main):006:0> Math.sqrt(5)6=> 2.236067977499797irb(main):007:0> Math.sin(0)8=> 0.09irb(main):008:0> Math.acos(1)10=> 0.0Methods
Defining a Method
We can define a method using def and end, so a method that prints Hello World would look like this:
1def hi2 puts "Hello World"3endOr, in the shell
1irb(main):017:0> def hi2irb(main):018:1> puts "Hello World"3irb(main):019:1> end4=> :hiCalling 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
1irb(main):020:0> hi2Hello World3=> nil4irb(main):021:0> hi()5Hello World6=> nilMethod Parameters
We can define hi such that it takes a name parameter like so:
1def hi(name)2 puts "Hello #{name}"3endAlso note how string interpolation/templates can be done in the above string
1irb(main):026:0> hi("bob")2Hello bob3=> nilWe can also call methods on an object, for example name by using either the method name with or without parenthesis as mentioned before
1name.capitalize1name.capitalize()We can then implement that in our hi method
1def hi(name)2 puts "Hello #{name.capitalize}"3endWhich can be called like:
1hi("bob")or
1hi "bob"Classes
Classes are defined using the class keyword
1class Greeter2 def initialize(name = "World")3 @name = name4 end5
6 def say_hi()7 puts "Hi #{@name}"8 end9
10 def say_bye()11 puts "Hi #{@name}"12 end13endWe can create an instance of the Greeter class by using Greeter.new, like so
1greeter = Greeter.new("bob")And we can then use it with:
1irb(main):029:0> greeter.say_hi2Hi bob3=> nil4irb(main):030:0> greeter.say_bye5Hi bob6=> nil