What's the best way to create methods dealing with an object of acertain class?

L

Leif K-Brooks

I want to add a method to be run on Strings. Currently, I'm just adding
it on to the String class. Should I be subclassing it instead? Creating
a method which takes a String as an argument?
 
B

Ben Giddings

Lyle said:
I have mixed feelings about re-opening built-in classes (like String) to
add new methods to them, even though the provision for this is one of
Ruby's attractions. My concern is that people get used to the built-ins
and expect certain standard behaviors from them; augmenting or otherwise
changing them could create confusion for other people looking at your code.

I think one way this has been done very effectively is the "Time" class.
The standard one contains a certain set of commands, but if you want more,
you simply "require 'time'" and it now has a bunch more methods, like
"iso8601".

The other way this has been done very well is with 'yaml'. If you require
this module, *everything* gains a "to_yaml" method. The name makes it
clear that you shouldn't expect that method to appear without 'yaml'.

As long as you're not changing the behaviour of any built-in methods, and
you make it clear the methods aren't "native", you should be ok.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top