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