Ruby .() - shorthand for method "call"
It would be fair to claim that the .call
method, let it be the class method or the instance method, is one of the most common methods in a class. It exists in every service object and in more places.
This is exactly why there is a shorthand built into the language to call the #call
method. This is the dot parenthesis (.(args)
).
On instances
When you use the .(args)
method on an instance of an object, you call its call
method.
class MyService
def call(what = 'Ruby')
puts "#{what} is the best!"
end
end
Now you call an instance with instance.(args)
.
service = MyService.new
service.() # => "Ruby is the best!"
service.("Rails") # => "Rails is the best!"
service.('Sinatra') # => Sinatra is cool!
Calling service.()
is synonymous with service.call()
.
On classes
The shorthand also works in classes. If you have a class method (static method), you can call it using .()
on a call.
class MyService
def self.call(what = 'Ruby')
puts "#{what} is the best!"
end
end
Usage:
MyService.() # => "Ruby is the best!"
MyService.('Rails') #=> "Rails is the best!"
MyService.('Sinatra') # => Sinatra is cool!
On Proc
procs
are a block of encapsulated Ruby code which is an instance of the Proc
class. You run a proc by calling its #call
method. As with instances of any class, .()
notion will call its #call
method and execute the code.
is_cool = proc { |what = 'Ruby' | "#{what} is cool!" }
is_cool.() # => Ruby is cool!
is_cool.('Rails') # => Rails is cool!
is_cool.('Sinatra') # => Sinatra is cool!
Conclusion
Each language has its superpowers. C and C++ are ridiculously fast and great for systems development. Python is great for AI and ML. Erlang is great for building resilient fault-tolerant applications. Ruby focuses on keeping the developer happy.
The dot-parenthesis shorthand reduces the necessity of explicitly mentioning the call
label of the method. This results in a cleaner and neater-looking Ruby code. While I personally love the shorthand, I see many not using it.
Do you like the shorthand?
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.