LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby】ダックタイピングとは

Last updated at Posted at 2022-09-26

環境

Rails 6.0.1
Ruby 2.6.3
PostgreSQL 11.16

ダックタイピングとは

特定のクラスと結びつかない、クラスを跨ぐパブリックインターフェースを取り決め実装する作法。
下記の例はbarkメソッドがダックタイプされていると言える。
もっと複雑な実装になってくるとbarkメソッドをmoduleにまとめて共通化する方が良さそう。

class Cat
  def bark
    puts 'ニャーニャー'
  end
end

class Dog
  def bark
    puts 'ワンワン'
  end
end

mike = Cat.new
poti = Dog.new

mike.bark
#=> 'ニャーニャー'
poti.bark
#=> 'ワンワン'

継承よりもダックタイピングを積極的に使うこと

継承が設計上必要でなければ、ダックタイピングで楽しようとのこと。

class Animal
  def bark
  end
end

class Cat < Animal
  def bark
    puts 'ニャーニャー'
  end
end

class Dog < Animal
  def bark
    puts 'ワンワン'
  end
end

参考

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