Search code examples
rubyoopmethodsnew-operator

New() method used in class definition to return a new object of itself in Ruby


I'm studying this snippet:

def self.from_file(file_name)
  new(File.readlines(file_name))
end

How does this code work? Does it only work for class methods? I understand this is supposed to return a new object of the class it was defined in.


Solution

  • new in Ruby is not an operator, it is simply a method from Class so you're just calling the new method with the class as the implicit receiver, you could also say:

    self.new(File.readlines(file_name))
    

    if you wanted to be explicit about what you're doing. As far as what it does, it:

    Calls allocate to create a new object of class’s class, then invokes that object’s initialize method [...]. This is the method that ends up getting called whenever an object is constructed using .new.