17
15

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 5 years have passed since last update.

クラスメソッドに alias を付ける

Posted at

いい例を思いつかなかったので適当なサンプルだが、例えば以下のように alias を使ってメソッドに別名を付けたい場合、クラスメソッドだと上手く行かない。

class Status
  STATUS = {
    0 => "open",
    1 => "close",
    2 => "suspend",
    9 => "error",
  }
  def self.name(code)
    STATUS[code]
  end
  alias :[] :name
end
#=> undefined method `name' for class `Status' (NameError)

alias_method でも駄目。

class Status
  STATUS = {
    0 => "open",
    1 => "close",
    2 => "suspend",
    9 => "error",
  }
  def self.name(code)
    STATUS[code]
  end
  alias_method :[], :name
end
#=> `alias_method': undefined method `name' for class `Status' (NameError)

結局以下のようにしたら出来た。

class Status
  STATUS = {
    0 => "open",
    1 => "close",
    2 => "suspend",
    9 => "error",
  }
  def self.name(code)
    STATUS[code]
  end

  class << self
    alias :[] :name
  end
end

puts Status.name(0) #=> open
puts Status[9]      #=> error

alias_method でも同じようにやれば出来る。

  class << self
    alias_method :[], :name
  end

参考

alias
http://docs.ruby-lang.org/ja/2.1.0/doc/spec=2fdef.html#alias

instance method Module#alias_method
http://docs.ruby-lang.org/ja/2.1.0/method/Module/i/alias_method.html

How to alias a class method - Ruby
http://www.justskins.com/forums/how-to-alias-a-102105.html

alias_method for static method - Ruby Forum
https://www.ruby-forum.com/topic/112031

17
15
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
17
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?