Chris Barrett
Chris Barrett

Reputation: 526

Is there a ruby equivalent to the php __invoke magic method?

Is there an equivalent to the php __invoke method in ruby?

e.g

class Test {
    public function __invoke() {
        echo "invoked";
    }
}

$test = new Test();
$test(); // prints invoked

Upvotes: 1

Views: 114

Answers (1)

Damiano Stoffie
Damiano Stoffie

Reputation: 897

Not the same exact thing but it should do the job

class Test
  def self.call
    puts "invoked self.call"
    return new
  end

  def call
    puts "invoked call"
  end
end

t = Test.()
t.()

You can use the .() syntax on both classes and objects, since classes are objects. .() is just a shorthand for .call

Upvotes: 1

Related Questions