On Sun, May 20, 2007 at 03:30:15AM +0900, Eli Bendersky wrote:
> In my application I need an "edit_distance" method that computes the
> Edit Distance (Also called Levenshtein Distance, see this:
> http://en.wikipedia.org/wiki/Levenshtein_distance) between two
> strings. I wonder where is the right place to put this method. I have
> a "utils" Ruby file with various extensions to classes and modules
> that make my life easier. So there are two options:
> 
> 1) Have a global (Kernel) method named "edit_distance" that accepts
> two strings
> 2) Add a "edit_distance_from" method to the String class that accepts
> the "other" string
> 
> Which approach is better, in your opinion ?

If you want to publish this for others to use, rather than just for your own
private use, then neither of these is a good idea. I'd go with:

3) Make it a class method of your own distinct module

This avoids accidental pollution of namespace or system classes. Then,
people can use MyUtils.edit_distance(a,b), or if they want, can explicitly
"include MyUtils" to be able to do "edit_distance(a,b)" directly.

This is the approach taken by Ruby's own Math library for functions like
sqrt:

irb(main):001:0> Math.sqrt(9)
=> 3.0
irb(main):002:0> include Math
=> Object
irb(main):003:0> sqrt(9)
=> 3.0

Regards,

Brian.