Created
August 19, 2012 07:03
-
-
Save maraigue/3393047 to your computer and use it in GitHub Desktop.
[Ruby] def文によらずに特異メソッドを定義する To define singleton methods without `def' sentence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ---------- definition ---------- | |
class Object | |
def define_singleton_method(name, method = nil, &block) | |
unless !!(method) ^ !!(block) | |
raise ArgumentError, "Only one method should be given" | |
end | |
source_object = self | |
Module.new do | |
define_method(name, method || block) | |
source_object.extend(self) | |
end | |
end | |
end | |
# ---------- usage ---------- | |
if $0 == __FILE__ | |
def print_hoge(obj) | |
begin | |
puts obj.hoge | |
rescue NoMethodError | |
puts "[Method `hoge' not found]" | |
end | |
end | |
str = "hoge" | |
print_hoge(str) # => "[Method `hoge' not found]" | |
str.define_singleton_method(:hoge) do | |
"HOGEHOGE" | |
end | |
print_hoge(str) # => "HOGEHOGE" | |
str.define_singleton_method(:hoge, ->{ "PIYOPIYO" } ) | |
print_hoge(str) # => "PIYOPIYO" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment