0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

rubyのForwardableライブラリの使い方

0
Last updated at Posted at 2025-12-31

rubyでForwardableライブラリは以下のように使います
https://docs.ruby-lang.org/ja/latest/class/Forwardable.html

require 'Forwardable'

class Bar
  def sample_method;  p "エイリアスでも定義します"; end
  def sample_method2; p "2"; end
  def sample_method3; p "3"; end
end

class Foo
  extend Forwardable

  def initialize
    @q ||= Bar.new
  end

  # 移譲するメソッドに別名を定義
  # 移譲先のオブジェクト、正式な名前、エイリアス名
  def_delegator :@q, :sample_method, :same_sample_method

  # 複数メソッドをまとめて移譲
  def_delegators :@q, :sample_method, :sample_method2, :sample_method3
end

Foo.new.same_sample_method         # "エイリアスでも定義します"
Foo.new.sample_method              # "エイリアスでも定義します"
Foo.new.sample_method2             # "2"
Foo.new.sample_method3             # "3"

こちらの記事でも学ばせて頂きました!
https://qiita.com/huydx/items/9335b4237051330523d3

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?