Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Split string at character, counting from the right side

Tags:

string

split

ruby

Short version -- How do I do Python rsplit() in ruby?

Longer version -- If I want to split a string into two parts (name, suffix) at the first '.' character, this does the job nicely:

name, suffix = name.split('.', 2) 

But if I want to split at the last (rightmost) '.' character, I haven't been able to come up with anything more elegant than this:

idx = name.rindex('.') name, suffix = name[0..idx-1], name[idx+1..-1] if idx 

Note that the original name string may not have a dot at all, in which case name should be untouched and suffix should be nil; it may also have more than one dot, in which case only the bit after the final one should be the suffix.

like image 850
lambshaanxy Avatar asked Dec 04 '09 00:12

lambshaanxy


People also ask

How do I split a string by character count?

Use range() function and slice notation to split a string at every character count in Python.

How do you split a character in a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


1 Answers

String#rpartition does just that:

name, match, suffix = name.rpartition('.') 

It was introduced in Ruby 1.8.7, so if running an earlier version you can use require 'backports/1.8.7/string/rpartition' for that to work.

like image 146
Marc-André Lafortune Avatar answered Sep 20 '22 06:09

Marc-André Lafortune