Created
December 9, 2010 12:51
-
-
Save deepak/734679 to your computer and use it in GitHub Desktop.
defining a singleton method on a attribute of an instance of a class
This file contains hidden or 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
# defining a singleton method on a attribute of an instance of a class | |
# which method is recommended, define_singleton_methods is short-and-sweet. benchmark. | |
class FooNestedDef | |
attr_accessor :info | |
def initialize | |
@info = [] | |
# NOTEL mindbending - def inside a def works. is this legal? | |
def @info.to_s | |
self.join(',') | |
end | |
end | |
end | |
# TODO: works on 1.9 Defined in SOAP::Mapping::define_singleton_method in 1.8 | |
class FooDefineSingleton | |
attr_accessor :info | |
def initialize | |
@info = [] | |
@info.define_singleton_method(:to_s) { self.join(',') } | |
end | |
end | |
class FooInstEval | |
attr_accessor :info | |
def initialize | |
@info = [] | |
@info.instance_eval do | |
class << self | |
def to_s | |
self.join(',') | |
end | |
end | |
end | |
end | |
end | |
class FooExplicit | |
attr_accessor :info | |
def initialize | |
@info = [] | |
class << @info | |
def to_s | |
self.join(',') | |
end | |
end | |
end | |
end | |
__END__ | |
f = FooNestedDef.new | |
f.info << "x" << "y" | |
p f.info.to_s | |
p f.info.method(:to_s).owner | |
f = FooDefineSingleton.new | |
f.info << "x" << "y" | |
p f.info.to_s | |
p f.info.method(:to_s).owner | |
f = FooInstEval.new | |
f.info << "x" << "y" | |
p f.info.to_s | |
p f.info.method(:to_s).owner | |
f = FooExplicit.new | |
f.info << "x" << "y" | |
p f.info.to_s | |
p f.info.method(:to_s).owner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment