On 06/05/06, Leslie Viljoen <leslieviljoen / gmail.com> wrote:

> ie. my function needs strings in culy braces. So the natural thing for
> me would be this:
>
> class String
>   def curlify
>     "{"+self+"}"
>   end
> end
>
> This is where I need the curlies and it makes sense for them to be there.

But then you've tampered with the very fabric of reality (HPL would be
proud) [1].

You could just modify the object you were passed:

def func_that_needs_strings_to_have_a_curlify_method(str)
  def str.curlify
    "{" + self + "}"
  end

  # do something with str
end

This has the side effect on permanently adding a curlify method to whatever
str points at, but not all Strings in the universe.

You might not want that, of course - but it has less impact than
modifying all strings. (If you only wanted that method to apply with your
function, you could dup the object you were passed before meddling
with it.

Obviously this example is a bit contrived, but if you were redefining
something like the length() method, it would be saner to limit the effect
of that.

[1] The ability to meddle with the fabric of reality is a feature, not
a bug, IMO. One of my fondest programming memories is the funny looks I got
when I discovered I could redefine Integers '+' method to always return 2.
I don't cackle often :)

--
Rasputin :: Jack of All Trades - Master of Nuns
http://number9.hellooperator.net/