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’
irb> 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.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
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 C. wrote:
Is there some way? Thanks a lot.
–
Iñaki Baz C.
[email protected]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)
iEYEARECAAYFAkisT1kACgkQJA/zY0IIRZYMfgCgsA7iBHQbirDuP+91V90C32pu
EdEAmwUg+0ueHuCgdesl4jvwnMFjNc7Q
=QgJ9
-----END PGP SIGNATURE-----
On Aug 20, 2008, at 9:31 AM, Iñaki Baz C. wrote:
irb> object.say_time
–> time
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
El Miércoles, 20 de Agosto de 2008, Michael G.
escribió:> 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
Thanks to both