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

Classes in Ruby are created with the class keyword:

class Dog
  #class body
end

Methods are created inside the Class:

class Dog
    def bark
        puts "Woof!"
    end
end

Objects

Objects are created by calling .new on a class:

frodo = Dog.new

You can then invoke the object's methods:

frodo.bark

..which prints:

Woof!"

Here's another example:

ar = Array.new
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]