8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ateam Group U-30Advent Calendar 2022

Day 14

【Ruby】initializeメソッド、引数の順番依存関係を取り除く

Last updated at Posted at 2022-12-13

initializeメソッドは引数の順番に依存している

次の例では、Fooのinitializeメソッドは3つの引数をとります。(hoge,piyo,bar)
デフォルト値はなく、それぞれの引数が必須です。

Class Foo
  def initialize(hoge, piyo, bar)
    @hoge = hoge
    @piyo = piyo
    @bar = bar
  end
end

ここで重要なのは引数を正しい順番で渡さないといけないことです。
newメソッドは引数の順番に依存します。

Foo.new(1,2,3)
=> hoge=1
=> piyo=2
=> bar=3

Foo.new(3,1,2)
=> hoge=3
=> piyo=1
=> bar=2

Foo.new(2,3,1)
=> hoge=2
=> piyo=3
=> bar=1

Rubyのinitializeメソッドの引数の順番の依存を取り除く方法

1. ハッシュを使う

Class Foo
  def initialize(args)
    @hoge = args[:hoge]
    @piyo = args[:piyo]
    @bar = args[:bar]
  end
end

# 引数にデフォルト値を設定する場合
Class Foo
  def initialize(args)
    @hoge = args[:hoge] || 12
    @piyo = args[:piyo] || 14
    @bar = args[:bar]
  end
end

initializeメソッドは引数をargsのみ設定しています。
argsはハッシュであり、入力の全てが含まれます。
initializeメソッドはこのハッシュから必要な引数を取得できます。
この手法を活用すれば、引数の順番に対する依存が全て取り除かれ、初期化の際に使われる引数やデフォルト値の追加および削除がしやすくなります。

Foo.new(
  :hoge => 1,
  :piyo => 2,
  :bar => 3
)
=> hoge=1
=> piyo=2
=> bar=3

Foo.new(
  :hoge => 11,
  :bar => 22,
  :piyo => 33
)
=> hoge=11
=> piyo=33
=> bar=22

2. キーワード引数を使う

class Foo
  def initialize(hoge: 1, piyo: 2, bar: 3)
    @hoge = hoge
    @piyo = piyo
    @bar = bar
  end
end
Foo.new(
    hoge: 1, 
    piyo: 2, 
    bar: 3
)
=> hoge=1
=> piyo=2
=> bar=3

Foo.new(
    hoge: 11, 
    bar: 22, 
    piyo: 33
)
=> hoge=11
=> piyo=33
=> bar=22

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?