Gundam Meister
Gundam Meister

Reputation: 1505

Ruby: self.call inside a class

Is there any difference between these two?

class Asdf
   def self.call
      puts "111"
   end
end

and

class Asdf
  def self.call
    new.call
  end

  def call
    puts "222"
  end
end

both can be called with Asdf.call . Is one a syntactic sugar of the other? Any performance difference between the two?

Upvotes: 1

Views: 1885

Answers (1)

tadman
tadman

Reputation: 211560

This depends entirely on what sort of data you're going to need for context when responding to that method call.

If there's no state involved, the class method approach works better since it doesn't require creating a temporary, and ultimately useless object.

Upvotes: 1

Related Questions