Grasping methods and monkey-patching?

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.

Rafal

On Sat, Mar 30, 2013 at 4:49 PM, Rafal C. [email protected] wrote:

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.

Or perhaps just

class Object
def is_i?
self.is_a? Integer
end
end

OK, thanks both of you.

On Sat, Mar 30, 2013 at 11:30 PM, Peter H. <
[email protected]> wrote:

Or perhaps just

class Object
def is_i?
self.is_a? Integer
end
end

Herewith I call the “useless use of self award” (UUOSA) to life. We
have a
first nominee. :slight_smile:

SCNR

Cheers

robert

PS: That would have been a good posting for yesterday…

Herewith I call the “useless use of self award” (UUOSA) to life. We
have a
first nominee. :slight_smile:

Yeah, is_i? was just an example but I guess it would qualify!

Is this award similar to the “egregious use of cat” in the *nix
command line world?

On Tue, Apr 2, 2013 at 5:58 AM, Robert K.

On Tue, Apr 2, 2013 at 10:00 PM, tamouse mailing lists <
[email protected]> wrote:

Is this award similar to the “egregious use of cat” in the *nix
command line world?

Exactly. See Partmaps.org

Kind regards

robert

On Tue, Apr 2, 2013 at 6:04 PM, Rafal C. [email protected] wrote:

Herewith I call the “useless use of self award” (UUOSA) to life. We
have a
first nominee. :slight_smile:

Yeah, is_i? was just an example but I guess it would qualify!

Nah, you missed the point of the award.

Cheers

robert