Grag808
Grag808

Reputation: 45

Classes and class return variables

I need a class to return another class, but fail to do so. Can you explain me why that happens? Here I am not including Temperature class as I think that is irrelevant.

class Celsius
  attr_accessor :temp
  def initialize(cel)
    return Temperature.new({:c =>cel})
  end
end

class Fahrenheit
  def initialize ( far )
    Temperature.new({:f => far})
  end
end 

I want to call Fahrenheit class to return a Temperature class

puts Fahrenheit.new(0) #=> returns  Fahrenheit class instead of Temperature 

In Celsius, I tried to use return, but it did not help.

Upvotes: 0

Views: 109

Answers (3)

Grag808
Grag808

Reputation: 45

Just to show resulting code. So simple, but still i had to ask :)

class Celsius
    def.self.new(cel)
        return Temperature.new({:c => cel})
    end
end

Upvotes: 0

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

Fahrenheit class instead of Temperature

This is correct because ::new consctuctor returns a newly created instance of the class, which was specified Temperature. But #initialize is really not a class constructor, it is just an initialization callback method.

You can use the following scheme:

far = Fahrenheit.new( 0 )
far.to_c # => Celsius

and the Fahrenheit class to the scheme:

class Fahrenheit
   def initialize( far )
      @temp = far
   end

   def to_c
      Celsius.new @temp
   end
end

In order to detect whether the class belongs to a Temperature class, just inherit Fahrenheit from it, and check as follows:

class Fahrenheit < Temperature
end

far = Fahrenheit.new
far.is_a?( Temperature )
# => true

Upvotes: 2

sepp2k
sepp2k

Reputation: 370102

The return value of initialize is not used in any way by new, so returning something from initialize serves no purpose. The only way to make Foo.new return something other than a Foo would be to override new directly, but that's usually not a good idea as it would be very confusing to the reader of your code.

If you have no intention of creating instances of your Celsius and Fahrenheit classes, they probably shouldn't be classes in the first place. In this case it would seem most sensible to me if your Temperature class had class methods celsius and fahrenheit.

Upvotes: 1

Related Questions