17
16

More than 5 years have passed since last update.

Ruby | 「call」メソッド の Syntax Sugar 「.()」 について

Last updated at Posted at 2014-09-05

Ruby | 「call」メソッド の Syntax Sugar 「.()」 について

概要

RubyKaigi で 登壇予定の Satoshi Egi 氏 の
egison-ruby を読んでいて「ん??」という文法がありました。

件のコードがこちら。

        with(List.(*_, _x, *_)) do

List.() なんて書き方ははじめてみました。

「call」メソッド の Syntax Sugar により「.()」 と記述できることを活用しています。

サンプルコード

require 'tbpgr_utils'

class Hoge
  def self.call(msg)
    msg
  end
end

class Hige
  def call(msg)
    msg
  end
end

class Parent
  def self.call(msg)
    msg
  end
end

# 継承も使えます
class Child < Parent
end

module MyModule
  def call(msg)
    msg
  end
end

# Mix-inも使えます
class Includer
  include MyModule
end

bulk_puts_eval binding, <<-EOS
Hoge.("hoge")
Hoge.call("hoge")
Hige.new.("hige")
Hige.new.call("hige")
Child.("child")
Child.call("child")
Includer.new.("includer")
Includer.new.call("includer")
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

$ ruby ruby_implicit_send_call.rb
Hoge.("hoge")                 # => "hoge"
Hoge.call("hoge")             # => "hoge"
Hige.new.("hige")             # => "hige"
Hige.new.call("hige")         # => "hige"
Child.("child")               # => "child"
Child.call("child")           # => "child"
Includer.new.("includer")     # => "includer"
Includer.new.call("includer") # => "includer"

参照

17
16
13

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
16