Scaling and the keyword 'self'

I have the following code:

def self.ftoc(temp_in_fahrenheit)
     (temp_in_fahrenheit - 32) * 5.0/9.0
end

def self.ctof(temp_in_celcius)
     (temp_in_celcius * 9.0/5.0) + 32
end

def calculate_temperatures
    @f = Temperature.ctof(@c) if (@f == nil && @c != nil)
    @c = Temperature.ftoc(@f) if (@c == nil && @f != nil)
end

It works great. However, if I changed the code to

def calculate_temperatures
    @f = self.ctof(@c) if (@f == nil && @c != nil)
    @c = self.ftoc(@f) if (@c == nil && @f != nil)
end

I get an error

undefined method 'ftoc' for #<Temperature:0x000000025486a0 @f=50>

I would think that the self, as an example of the Temperature class, would be able to use the ctof / ftoc methods, but that is not the case. Can someone help me understand what I am missing?

Many thanks.

+4
source share
2 answers

An internal method selfis an instance Temperature. Inside classis an instance classthat has a name Temperature.

Try the following:

class Temperature
  puts "Inside class: self is #{self}, Temperature is #{Temperature}"

  def meth
    puts "Inside method: self is #{self}, Temperature is #{Temperature}"
  end
end

Temperature.new.meth

However, inside classthey are equivalent:

class Temperature
  def self.meth ; end
  def Temperature.meth ; end
end

method, self , Temperature, class, - .

, self.class. , :

class Temperature
  def meth
    Temperature.ctof(...)
    self.class.ctof(...)
  end
end
+2

ftoc ctof , self. calculate_temperatures - .

, self.class:

def calculate_temperatures
    @f = self.class.ctof(@c) if (@f == nil && @c != nil)
    @c = self.class.ftoc(@f) if (@c == nil && @f != nil)
end
+1

All Articles