Jay-Ar Polidario Jay-Ar Polidario - 5 months ago 16
Ruby Question

How to define unnamed method in Ruby?

I was reading on cells gem when I suddenly got curious on its implementation of unnamed method in its documentation.

Particularly the code below:

CommentCell.(@comment).()


and

cell(:comment, @song).(:index)


where it uses
.(arguments)
without a method name.

I am certain the answer is just somewhere in the source code itself. But briefly looking at
Cell::ViewModel
doesn't immediately help me, so I was just wondering first if anyone knows how to do this before I thoroughly inspect the source code, and hopefully satisfies my curiosity.

I can see some uses of this in the app that I will be making soon.

Answer

.() looks like a method invocation missing the method name. This is syntactic-sugar that invokes the call method. It can be used with any object that defines a call method and works with Proc or lambda.

class Test
  def call
    puts "test"
  end
end

t = Test.new
t.()
# => "test"
lambda {puts "test"}.()
Proc.new {puts "test"}.()

But there are other possible solutions to react on .(). You could override method_missing or set an alias.

class Test
  def test
    puts "test"
  end

  alias call test;
end

t = Test.new
t.()
# => "test"