LoginSignup
2
1

More than 5 years have passed since last update.

クラスの動的継承。~僕はまだまだrubyのことを知らない~

Posted at

参考:知って得する!55のRubyのトリビアな記法

ずっと読もうと思っていたこの記事をやっと最近読んでいて、
こんなのあったんだとびっくりしたので、ご報告になります。

動的継承(23.)


class Male
  def laugh
    'Ha ha ha!'
  end
 end

 class Female
  def laugh
    'Fu fu fu..'
  end
 end

 class Me < [Male, Female][rand 2]
 end

# 以下はランダムでMale,Femaleが継承されメソッドが呼ばれている。
 Me.superclass # => Female
 Me.new.laugh # => 'Fu fu fu..'

動的継承は継承先をランダムで決めることができます。
あまり、仕事で使うシーンは思い浮かんでないのですが、
描画系のコードで使えそうだなと思いました。:joy:

2
1
4

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
2
1