LoginSignup
5
3

More than 5 years have passed since last update.

別名でも呼べるようにしたいという理由でaliasを使うのは間違っているのかもしれない

Last updated at Posted at 2017-11-21
class C
  def a
    1
  end

  alias b a
end

class C2 < C
  def a
    super + 100
  end
end

C2.new.a                        # => 101
C2.new.b                        # => 1

C2.new.b も 101 になるのを期待していたのでちょっとはまりました。
安易に alias を使ったのが間違いでした。

いろんなライブラリを見ると別名でも呼べるようにしたいという理由で alias や alias_method が多用されている気がしますが、b から a を呼び出すのと alias b a は違うことを覚えといた方がよさそうです。

元のメソッドを呼ぶだけのコードを alias に置き換えたりするようなリファクタリングにも注意が必要ですね。

5
3
1

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
5
3