[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: learning the "Ruby way"

T. Onoma

11/20/2003 9:24:00 AM

how's this?

y = nil
newlst = lst.collect { |x|
y == x[0..0] ? x : y=x[0..0]; [ "-#{x[0..0]}-", x ] }
}.flatten

in future ruby2 y=nil may not be needed.

-t0

> **Hobby-programmer alarm**
>
> Hello!
> I am trying to learn Ruby, but with the goal of understanding new
> elegant solutions, not to repeat the same messy solutions I usually
> come up with.
> Here is an example I would like to use to improve my understanding.
> Any pointers would be great.
>
> Problem:
> I have a sorted list ('alfred', 'boris', 'bruce', 'claire', 'dean', 'donald')
> and would like to generate or return ('-a-', 'alfred', '-b-', 'boris',
> 'bruce', '-c-', 'claire', '-d-', 'dean', 'donald').
>
> Here's my solution:
> lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']
> prev = ''
> newlst = Array.new
> lst.each { |cur|
> if cur[0..0] != prev
> newlst.push("-#{cur[0..0]}-")
> end
> newlst.push(cur)
> prev = cur[0..0] }
>
> Is this the "Ruby way" of solving this problem? I doubt it, defining
> "helper variables" like this is what had to be done in Basic, and my
> solution doesn't demonstrate the high degree of readability Ruby is often
> praised for.
>
> Any useful suggestions for me? I'd be very grateful!
> Mark
>
>