objects-info
TRANSCRIPT
Ruby Objects
--Sowjanya Mudunuri
References
• The Ruby Programming Language by David Flanagan and Yukihiro Matsumoto
• Beginning Ruby by Peter Cooper
• Disclaimer: This notes is composed from the above referenced books. This presentation is used to help fellow friends who are trying to learn ruby.
Ruby Objects
• All Values are objects in Ruby
• Ruby is a strictly object oriented language
• when we work with objects in ruby we are really working with object references
p = “Cloud”
we are storing a reference to the String object “Cloud” into p
Passing Objects by reference & the Object lifetime
• When we pass an object to a method in Ruby, it is an object reference that is passed to the method
• When ‘new’ is called on a class it allocates memory to hold an instance of the class and initializes the state of the newly created object by calling the ‘initialize’ method
• Ruby Objects never need to be explicitly deallocated
• Garbage Collection: Ruby automatically destroys objects that are no longer needed( there are no references to the object)
Object_ids
• Every object has an object identifier, a Fixnum, that you can obtain with the object_idmethod
• The value returned by object_id is constant and unique for the lifetime of the object
p = “Hello”
p.object_id
Object Equality
• equal? method is defined by Object class to test whether two values refer to the exact same object
• Most standard ruby classes define the == operator
• Example: Array, Hash, String classes define their == operator to make sense
a = “MyName”
b = “MyName”
a.equal?(b) returns false
a == b returns true
a.object_id
b.object_id
Defining your own == operator
class Point
attr_accessor :x, :y
def initialize(x,y)
@x = x
@y = y
end
def ==(other)
if other.is_a?(Point)
@x==other.x && @y==other.y
else
false
end
end
end
Object Conversion
• Ruby classes define methods that return a representation of the object as a value of a different class
• Examples: to_s , to_i, to_f, to_a
• Defining your own to_s methodclass Point
attr_accessor :x, :y
def to_s
“#{@x}, #{@y}”
end
end
Exercise Time!!
• Define a class named ‘Player’ and have an attribute named ‘name’ and ‘rank’
• Define the == operator on the ‘Player’ by checking the equality of ‘name’ and ‘rank’
• Define a to_s instance method on the ‘Player’ that returns “I am Sowjanya and my rank is 1” where ‘Sowjanya’ and ‘1’ needs to be string interpolated from name and rank attributes
• Well if you are confused about string interpolation now is the time to read about it :: Google ‘string interpolation in ruby’
Exercise Time!!
• Define a class named “Game” with attributes ‘name’ , ‘players’
• Instantiate a ‘Game’ by passing in the name and players and store it the variable ‘game’ Note: Players are an array of Player objects from your previous exercise
• get the object_id of ‘game’
• define a method that iterates through each player and prints it. Note: you can iterate through an array using ‘each’ operator go google it.