cpuSonicatt
cpuSonicatt

Reputation: 53

How can I split a String when I'm splitting around the last character in Ruby?

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?

Upvotes: 5

Views: 139

Answers (2)

Stefan
Stefan

Reputation: 114248

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"

Upvotes: 6

steenslag
steenslag

Reputation: 80095

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", ""]

Upvotes: 6

Related Questions