LoginSignup
1
1

More than 5 years have passed since last update.

オープンクラス

Last updated at Posted at 2016-01-27

オープンクラスとは

既存のクラスを自在に拡張するようなコードを書けること。

例. Numericクラスの拡張

selfが正の数なら0からselfの数まで1ずつ増やした配列を返すメソッドstepを定義してみる。

class Numeric
  def steps
    return [] if self <= 0

    0.upto(self).to_a
  end
end

p 10.steps  #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
p 8.steps   #=> [0, 1, 2, 3, 4, 5, 6, 7, 8]
p -20.steps #=> []
p 0.steps   #=> []
1
1
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
1
1