From: Josh Cheek Date: 2013-03-31T07:26:41+09:00 Subject: Re: Grasping methods like "to_s"? --bcaec554d4349118d604d92be150 Content-Type: text/plain; charset=ISO-8859-1 On Sat, Mar 30, 2013 at 4:49 PM, Rafal C. wrote: > Hi, I'm posting here to quickly ask you: how is one able to do something > like: > > "string".is_i? > > ...where "is_i?" is a method I created, on any object? This kind of goes > into monkey-patching I guess. Would I have to do: > > class String > # My method > end > > ...for every class I want that method to be available upon? So what if I > want a method called "is_i?" to be available for the String, Integer, > and Hash classes? Would I have to add that method to each of the classes > separately (like above)? > > Thanks, and I apologise for the, some say, n00b'iness of this question. > > Since all the classes you would want to put it on inherit from Object, you would define it on Object class Object def is_i? false end end class Integer def is_i? true end end "abc".is_i? # => false 123.is_i? # => true With that said, I'm going to recommend not doing this in any code you intend to maintain or distribute as a library, because it affects the environment. --bcaec554d4349118d604d92be150 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Sat, Mar 30, 2013 at 4:49 PM, Rafal C. <lists@ruby-forum.com>= wrote:
Hi, I'm posting here to quickly ask you: how is one able to do somethin= g
like:

=A0 =A0 "string".is_i?

...where "is_i?" is a method I created, on any object? This kind = of goes
into monkey-patching I guess. Would I have to do:

=A0 =A0 class String
=A0 =A0 =A0 # My method
=A0 =A0 end

...for every class I want that method to be available upon? So what if I want a method called "is_i?" to be available for the String, Inte= ger,
and Hash classes? Would I have to add that method to each of the classes separately (like above)?

Thanks, and I apologise for the, some say, n00b'iness of this question.=


Since all the classes you would want to put it on in= herit from Object, you would define it on Object

class Object
=A0 def is_i?
=A0 =A0 false
=A0 end
end

class Integer
=A0= def is_i?
=A0 =A0 true
=A0 end
end

"abc".is_i? # =3D> false
123.is_i? =A0 # =3D> tru= e


With that said, I'm goi= ng to recommend not doing this in any code you intend to maintain or distri= bute as a library, because it affects the environment.
--bcaec554d4349118d604d92be150--