# Recursion is not working well

Hi,

I wrote a recursion as follows:

s = :split_this_world_game
def brk(start,s)
ar = []
cp = (s =~ /[_]/)
ss = s[start + 1,cp] if cp != nil
return s if cp == nil
ar.push(ss)
return ar.push(brk(cp,s[cp+1,s.size - ss.size])).flatten
end
p brk(-1,s)

The above code output:

[“split”, “orld”, “_game”, “game”]

But I wanted it as : [“split”,“this”,“world”,“game”]

Can anyone help me to find out where I did the wrong?

Finally I fixed it:

s = :split_this_game_world
def brk(s)
ar = []
cp = (s =~ /[_]/)
ss = s[0…cp] if cp != nil
return s if cp == nil
ar.push(ss)
return ar.push(brk(s[cp+1,s.size - ss.size])).flatten
end
p brk(s)

#=>[“split”, “this”, “game”, “world”]

Can this code be shorten or more Rubystic(obviously not converting the
symbol to String in first place)?

Yes! I made it till now:

s = :split_this_game_world
def brk(s)
cp = (s =~ /[_]/)
ss = s[0…cp] if cp != nil
return s.to_sym if cp == nil
return [].push(ss.to_sym,brk(s[cp+1,s.size - ss.size])).flatten
end
p brk(s)

#=> [:split, :this, :game, :world]

Is it possible to make it more shorter?

Am 08.05.2013 14:24, schrieb Love U Ruby:

#=> [:split, :this, :game, :world]

Is it possible to make it more shorter?

Shorter is not automatically better.

Your variable and method names are too short (!)
and make reading of that code really painful.

My recursive version (for strings, not symbols):

def split_string(string)
first, rest = string.split(’_’, 2)
return [first] unless rest

`````` [first] + split_string(rest)
``````

end

split_string(‘this_is_a_test’)
=> [“this”, “is”, “a”, “test”]

More rubyish and even shorter (probably as short as possible)
but not recursive:

‘this_is_a_test’.split(’_’)

On 2013-05-08, at 8:24 AM, Love U Ruby [email protected] wrote:

#=> [:split, :this, :game, :world]

Is it possible to make it more shorter?

Posted via http://www.ruby-forum.com/.

If you don’t need recursion…

[1] pry(main)> def brk(s)
[1] pry(main)* s.to_s.split(/_/).map &:to_sym
[1] pry(main)* end
=> nil
[2] pry(main)> brk(:split_this_game_world)
=> [:split, :this, :game, :world]

Mike

The “`Stok’ disclaimers” apply.

:split_this_world_game.to_s.split( ‘_’ )
regex no parens:

:split_this_world_game.to_s.split /_/

~