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

nil

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

 

Creating Object

1. Creating a new Animal object

first_animal=Animal.new

2. Adding attributes

first_animal.name = “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

puts first_animal.name

It will print its name as

floyd

 

 

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: