Classes and Objects


Collapse Content

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:

word = String.new("hello")
ar = Array.new([1,2,3])
ha = Hash.new

Everything is an Object

In Ruby, absolutely everything is an object and belongs to a class. All classes inherit from the superclass Object. This means you can invoke all the methods of Object on everything in Ruby.

5.class  #=> Fixnum
true.class  #=> TrueClass
true.class.superclass #=> Object    

23.to_s  #=> "23"
nil.to_s  #=> ""

Note how calling to_s on 23 returned a string representation of 23. You can create a to_s method in your own classes to return a string representation of their instances.

Intro to the Challenges

In the challenges in this tutorial, you'll create a simple command-line program for storing and retrieving a store's product data. This program will be similar to a miniature version of Ruby on rails so you can learn about Ruby and Rails at the same time!

Challenge

  1. Create a class called Product.
  2. Inside the class, create a method called to_s. For now the method should just return a string "A product".
Hint for #1

Hint for #2

Challenge

Create a product class with a to_s method as described above.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

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