ogirginc ogirginc - 6 months ago 12
Ruby Question

Why is `self` needed inside a instance method?

A ruby newbie here going through Well Grounded Rubyist.

I couldn't understand, why do we need

self
in the
make_mates
instance method? When I run the code without
self
, it works same as
self
being included. Why do we need to call
make
on the object by using
self
?

Note: (I think) I know how
self
works & I'm only asking for this specific case, not a general explanation of
self
.

class Car
@@makes = []
@@cars = {}
attr_reader :make

def self.total_count
@total_count ||= 0
end

def self.total_count=(n)
@total_count = n
end

def self.add_make(make)
unless @@makes.include?(make)
@@makes << make
@@cars[make] = 0
end
end

def initialize(make)
if @@makes.include?(make)
puts "Creating a new #{make}!"
@make = make
@@cars[make] += 1
self.class.total_count += 1
else
raise "No such make: #{make}."
end
end

def make_mates
@@cars[self.make] # Why do we need self?
end

end

class Hybrid < Car
end

Car.add_make("Honda")
Car.add_make("Ford")

h = Car.new("Honda")
f = Car.new("Ford")
h2 = Car.new("Honda")

puts "Counting cars of same make as h2..."
puts "There are #{h2.make_mates}."
puts
puts "Counting total cars..."
puts "There are #{Car.total_count}."
puts

h3 = Hybrid.new("Honda")
f2 = Hybrid.new("Ford")

puts "There are #{Hybrid.total_count} hybrids on the road!"

Answer

You don't need it in that case.

You only need to refer to an attribute with self if you're assigning to it, to distinguish it from assigning to a local.

Comments