[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: [QUIZ] FizzBuzz (#126

seebs

6/3/2007 11:21:00 AM

My solution, which is probably awkward in its use of method mangling:

class Fixnum
@@old_to_s = 1.method(:to_s).unbind
def to_s
s = ((self % 3 == 0 ? "Fizz" : "") + (self % 5 == 0 ? "Buzz" : ""))
s.empty? ? @@old_to_s.bind(self).call : s
end
end

(1..100).each { |x| p x }

I wouldn't be surprised at all to find that there's a much cleaner way
to accomplish the override. The curious reader will note that this could
be shortened somewhat if we had something like that "it" feature some
were discussing.

-s

1 Answer

Chris Carter

6/3/2007 3:44:00 PM

0

On 6/3/07, Peter Seebach <seebs@seebs.net> wrote:
> My solution, which is probably awkward in its use of method mangling:
>
> class Fixnum
> @@old_to_s = 1.method(:to_s).unbind
> def to_s
> s = ((self % 3 == 0 ? "Fizz" : "") + (self % 5 == 0 ? "Buzz" : ""))
> s.empty? ? @@old_to_s.bind(self).call : s
> end
> end
>
> (1..100).each { |x| p x }
>
> I wouldn't be surprised at all to find that there's a much cleaner way
> to accomplish the override. The curious reader will note that this could
> be shortened somewhat if we had something like that "it" feature some
> were discussing.
>
> -s
>
>

My solution (see other thread) uses a lot of those same techniques.
My method was overriding #inspect instead of #to_s, so you don't need
to do anything crazy. Or you could just use an alias... :)

--
Chris Carter
concentrationstudios.com
brynmawrcs.com