Split string from the second occurrence of the character

There's nothing like a one-liner :)

str.reverse.split('-', 2).collect(&:reverse).reverse

It will reverse the string, split by '-' once, thus returning 2 elements (the stuff in front of the first '-' and everything following it), before reversing both elements and then the array itself.

Edit

*before, after = str.split('-')
puts [before.join('-'), after]

You could use regular expression matching:

str = "20050451100_9253629709-2-2"
m = str.match /(.+)-(\d+)/
[m[1], m[2]]  # => ["20050451100_9253629709-2", "2"]

The regular expression matches "anything" followed by a dash followed by number digits.

Tags:

String

Ruby