Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to use Classname.new keyword in ruby other than when creating an instance of an object in a main

Tags:

ruby

This class takes in a hash, and depending on the input, it converts temperatures.

class Temp
  def initialize(opt={})
    if opt.include?(:cold)
      @colddegree=opt[:cold]
    end
  end
  def self.from_cold(cel)
    Temp.new(:cold => cel) <= instance of class created in class method
  end
end

An instance of a class is created inside a class method. Why is it necessary to do so, and what it does it do, what is the reasoning behind it?

  • Why would we need to create an instance of a class inside the class instead of the main?
  • Why would it be used inside a class method? Can there be a time when it would be required inside a regular object methods?
  • What is it calling and what is happening when it is creating an instance inside a class method? what difference does it make?
like image 422
user2452062 Avatar asked Oct 11 '25 15:10

user2452062


1 Answers

Rubyists don't always use the word, but self.from_cold is a factory. This allows you to expose a Temp.from_cold(-40) method signature that programmers consuming your API can understand readily without having to concern themselves with the boilerplate of, say, learning that you have an implicitly required parameter named :cold.

It becomes extra useful when you have a work-performing object that needs to be initialized and then invoked, such as TempConverter.new(cel: -40).to_fahrenheit. Sometimes it's cleaner to expose a TempConverter.cel_to_fahr(-40) option to be consumed by other libraries. It's mostly just a way of hiding complexity inside of this class so that other classes with temp conversion needs don't have to violate the Law of Demeter.

like image 127
Daniel J. Pritchett Avatar answered Oct 14 '25 12:10

Daniel J. Pritchett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!