Mikk Poles Mikk Poles - 4 months ago 7
Ruby Question

Calling an instance method or a class method

I have a class:

Class Temp
def Temperature
puts "It's hot"
end
end


I can call an instance of that:

mytemp = Temp.new


I can call the method
Temperature
on it. How do I know if I am calling an instance class or class methods?

Answer

Lets define following class. I defined methods beginning with lowercase as everybody does.

class Temp
  def temperature
   puts "I am instance"
  end

  def self.temperature
   puts "I am class"
  end
end

t = Temp.new
t.temperature

-> "I am instance"


Temp.temperature

-> "I am class"


t = Temp.new
t.class.temperature

-> "I am class"

Hope it helps and makes things clear :)