Source From Here
Question
I know I can do the following, and it's just 3 lines:
But out of curiosity, is there a simpler way (
without semicolons) like:
Answers
Since Ruby 1.9 you can use the obj.singleton_class (Returns the singleton class of obj. ) method to access the singleton object of a class. This way you can also access thealias_method(new_name, old_name) method. The method itself is private so you need to invoke it with send. Here is your one liner:
For example:
Keep in mind though, that
alias will not work here.
Supplement
* [ Ruby Gossip ] Basic : 類別 - 關於 self
* [ 文章收集 ] alias vs alias_method
Question
I know I can do the following, and it's just 3 lines:
- class << self
- alias :generate :new
- end
- class_alias :generate, :new
Since Ruby 1.9 you can use the obj.singleton_class (Returns the singleton class of obj. ) method to access the singleton object of a class. This way you can also access thealias_method(new_name, old_name) method. The method itself is private so you need to invoke it with send. Here is your one liner:
- self.singleton_class.send(:alias_method, :generate, :new)
- class MyObj
- def objTest
- puts "objTest"
- end
- def MyObj.clsTest
- puts "clsTest"
- end
- self.singleton_class.send(:alias_method, :clsTest2, :clsTest)
- end
- obj = MyObj.new
- obj.objTest
- #obj.clsTest # NoMethodError: undefined method `clsTest' ...
- obj.class.clsTest
- MyObj.clsTest2
Supplement
* [ Ruby Gossip ] Basic : 類別 - 關於 self
* [ 文章收集 ] alias vs alias_method
沒有留言:
張貼留言