Classes and Objects

Premium Content - Free Preview

beta tutorial

This tutorial will teach you about Object-oriented programming in Ruby along with some useful Ruby methods. It assumes you're familiar with basic Ruby, covered in Learn Ruby. See the pages on Objects and Classes to understand how Objects and classes are used in programming in general.


Classes in Ruby are created with the class keyword:

class Dog
  #class body

Methods are created inside the Class:

class Dog
    def bark
        puts "Woof!"


Objects are created by calling .new on a class:

frodo =

You can then invoke the object's methods:


..which prints:


Here's another example:

ar =
ar.size #=> 0

Ruby provides literal shortcuts for creating instances of Strings, Arrays and Hashes without using .new:

word = "hello"  # created String
ar = [1,2,3]  #creates Array
ha = {}  #creates empty Hash

These are equivalent to:

End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]