Wednesday, March 19, 2008

1000.times better

Short code post. Just the story of how do you get someone looking into Ruby when they had already dismissed it as a fad. You know, the hype can blind you.

So the situation arrived when a friend needed to have a particular chunk of XML repeated 1000 times. No more, no less. Sounds stupid but it's just an oversimplified anecdote.

When he asked me for a quick script to do it for him, I saw an opportunity to show how Ruby would be a good tool for this job (insert promo here). Being a "show, don't tell" kind of guy, this was the code I presented him.


def thousand_repeater(string, repeats =1000)
repeats.times do
print "#{string}\n"
end
end


Not too fancy by any means. You just have to call it with the string you want, optionally provide the number of times you want it repeated and that's pretty much it.

Ex.: thousand_repeater "hello",3


The thing that got to him was actually the ability that Ruby gives you of doing something like "1000.times", compared to the more familiar (at least for him)

for(i=1; i<1000; i++)


Thats it.

3 comments:

page failed while rendering :username said...

Talvez menos interessante em termos de uso, mas mostra a natureza dinâmica do ruby:

>> mil = lambda {|s| 1000.times{ puts s}}

mil.call('teste')

Lambda e procs @ http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods

page failed while rendering :username said...

Vá. Só mais um giro :)
A lá rails :P

>> def mil
>> 1000.times { yield }
>> end

>> mil { print 'a' }

E este permite repetir qualquer chunk of code mil vezes ;)

E agora mostra ao teu amigo as classes que sao dinâmicas. E as instancias que podem receber métodos em runtime. Ducktyping. :|

é melhorar parar :P

Em resumo. Quando se conhece o ruby existe uma tendência para o java ficar menos interessante :P

JP Antunes said...

Tu estás lá Nuno!

Acabaste de me dar um ideia para um futuro post.

Haverá ou não um "right way" de escrever código numa linguagem que não tem um "single way" de o fazer.

Nos teus dois exemplos (ambos muito bons, alias) introduzes conceitos e métodos pouco obvios numa perspectiva de manutenção de código (closures, yield). Claro que esse também não era o objectivo do meu script, mas ainda assim...

Obrigado pelos teus comentários.