Skip to content

Instantly share code, notes, and snippets.

@maraigue
Created August 19, 2012 07:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraigue/3393047 to your computer and use it in GitHub Desktop.
Save maraigue/3393047 to your computer and use it in GitHub Desktop.
[Ruby] def文によらずに特異メソッドを定義する To define singleton methods without `def' sentence
# ---------- 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