Home > Back-end >  How can I split a String when I'm splitting around the last character in Ruby?
How can I split a String when I'm splitting around the last character in Ruby?

Time:12-13

I'm trying to split a String in two, then assign it to two variables.

When I split the String around one of the middle characters, it returns:

a, b = *"12x45".split("x")
>> a: "12"
>> b: "45"

When I split the String around the first character, it returns:

a, b = *"x2345".split("x")
>> a: ""
>> b: "2345"

But when I split the String around the last character, it returns:

a, b = *"1234x".split("x")
>> a: "1234"
>> b: nil

I would have expected b to be "" instead of nil. Is there a different way to achieve this?

Solution:
Using #split's optional 2nd parameter, you can achieve the following:

a, b = "1234x".split("x", -1)
>> a: "1234"
>> b: ""

CodePudding user response:

split takes an optional second parameter which limits the amount of splits. When this limit is set to -1 it behaves like " If limit is negative, it behaves the same as if limit was nil, meaning that there is no limit, and trailing empty substrings are included" (from the docs). So:

"1234x".split("x", -1) # => ["1234", ""]

CodePudding user response:

If there are at most two parts, you can also use partition which defaults to empty string if one part is "missing". As opposed to split it also returns the separator as the middle element: (you can assign it to _ if you don't need it)

a, _, b = "12x45".partition("x")
a #=> "12"
b #=> "45"

a, _, b = "1234x".partition("x")
a #=> "1234"
b #=> ""

a, _, b = "x2345".partition("x")
a #=> ""
b #=> "2345"
  • Related