Roshan Book

My Tech Notebook

Learning Ruby – Part 2 Classes and Objects

Creating Class

1. Declaring a class

class Animal

Notice while declaring a class, it starts with a capital letter

2. Declaring an attribute

attr_accessor :name,:age,:trait

3. Ending the class


Now we have a class named Animal with three attributes – name, age and trait


Creating Object

1. Creating a new Animal object

2. Adding attributes = “Floyd”

first_animal.age = “93”

first_animal.trait = “annoying”

While adding text surround it with “”, for number no need for double quotes


Accessing the trait

1. Calling name of first_animal


It will print its name as





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: