LoginSignup
0
2

More than 5 years have passed since last update.

alias

Posted at

alias

すでに存在するメソッドに別の名前を割り当てたい場合がある。
そのような時にはaliasを使用する。
aliasの引数にはメソッド名かシンボル名を指定する

メソッド名をそのまま書く場合: alias 別名 元の名前 
シンボルを使う場合:     alias :別名 :元の名前

以下の例はクラスC1とクラスC1を継承したクラスC2を定義している。
クラスC2ではhelloメソッドにold_helloという別名をつけた後にhelloメソッドを
再定義している。

ruby

class C1 # C1クラスの定義

  def hello #helloを定義
    "Hello"
  end

end

class C2 < C1 #C1クラスを継承してC2クラスを定義

  alias old_hello hello #別名old_helloを設定

  def hello #helloを再定義
    "#{old_hello},again"
  end

end


obj = C2.new
p obj.old_hello
p obj.hello


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