LoginSignup
6
3

More than 1 year has passed since last update.

Ruby | alias_method はメソッド / alias はキーワード

Last updated at Posted at 2017-09-27

alias_method

メソッドなのでオーバーライド出来る。

class User
  def full_name
    puts "Strawberry Kiwi"
  end

  # alias_method メソッドをオーバーライドする
  def self.alias_method(arg1, arg2)
    puts "alias_method : #{arg1} to #{arg2}"
  end

  # オーバーライドしたメソッドが呼ばれる
  alias_method :name, :full_name # alias_method : name to full_name

  # 同じくオーバーライドしたメソッドが呼ばれる
  self.alias_method :name, :full_name # alias_method : name to full_name
end

# メソッドのエイリアスはおこなわれていない
User.new.name # undefined method `name'

alias

言語キーワードなのでオーバーライドできない。

class User
  def full_name
    puts "Banana Orange"
  end
  
  # alias メソッドを定義する
  def self.alias(arg1, arg2)
    puts "alias : #{arg1} to #{arg2}"
  end

  # オーバーライドしたメソッドが呼ばれる
  self.alias :name, :full_name # alias : name to full_name

  # 言語キーワードとして実行される
  alias :name :full_name
end

# エイリアスが生成されている
User.new.name # Banana Orange

こんな風に、メソッド自体を引数として渡しているかのように書けるのも、alias がメソッドではなくてキーワードだから。(たぶん)

alias name full_name

環境

  • ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin15]

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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