Hi, I know that I can extend a Class instance (an object) with a
method(s) by doing:
object.extend Module
but can I do it in a "inline" way without the need of a module?
I just want something as follows:
time = Time.now
object.add_method 'def say_time(); return time; end'
> object.say_time
--> time
Note that I **don't** want to include the "add_method" in object class
or in Object class. This is, I don't want to "dirty" object class.
Also note that I can't use "object.extend Module" since the method
"say_time" must return a variable "time" value that I pass as an
argument.
Is there some way? Thanks a lot.
···
--
Iñaki Baz Castillo
<ibc@aliax.net>
I'll explain it by example:
a = "a"
#=> "a"
class << a
def fooify
return "foo #{self}"
end
end
a.fooify
#=> "foo a"
b = "b"
#=> "b"
b.fooify
#NoMethodError: undefined method `fooify' for "b":String
# from (irb):9
# from :0
···
On Aug 20, 2008, at 6:31 PM, Iñaki Baz Castillo wrote:
Hi, I know that I can extend a Class instance (an object) with a
method(s) by doing:
object.extend Module
but can I do it in a "inline" way without the need of a module?
I just want something as follows:
time = Time.now
object.add_method 'def say_time(); return time; end'
> object.say_time
--> time
Note that I **don't** want to include the "add_method" in object class
or in Object class. This is, I don't want to "dirty" object class.
Also note that I can't use "object.extend Module" since the method
"say_time" must return a variable "time" value that I pass as an
argument.
Is there some way? Thanks a lot.
--
Iñaki Baz Castillo
<ibc@aliax.net>
You can do this with singleton methods:
irb(main):001:0> object = Object.new
=> #<Object:0x304af8>
irb(main):002:0> def object.say_time; Time.now; end
=> nil
irb(main):003:0> object.say_time
=> Wed Aug 20 10:13:29 -0700 2008
···
On Aug 20, 2008, at 9:31 AM, Iñaki Baz Castillo wrote:
Hi, I know that I can extend a Class instance (an object) with a
method(s) by doing:
object.extend Module
but can I do it in a "inline" way without the need of a module?
I just want something as follows:
time = Time.now
object.add_method 'def say_time(); return time; end'
> object.say_time
--> time
--
Michael Granger <ged@FaerieMUD.org>
Rubymage, Architect, Believer
The FaerieMUD Consortium <http://www.FaerieMUD.org/>