Derek
Derek

Reputation: 12388

Retrieving last portion of string in Ruby?

Say I have a string "like_this_string" and I want to separate it into two parts: "like_this" and "string". So I can do this

first, last = "like_this_string".something
first == "like_this" # true
last == "string" # true

So the last part is always the string after the last "_" and the first part is always the string before the last "_". I would prefer a more efficient way of doing this than a combination of string to array, get last item, and then rejoin array (e.g. split, pop, join).

Upvotes: 1

Views: 113

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110755

Just to point out one more way:

*first, last = "like_this_string".split('_')
first = first.join('_')

first #=> "like_this"
last  #=> "string"

Upvotes: 1

matt
matt

Reputation: 535989

first, last = s[0..(ix=s.rindex("_"))-1], s[ix+1..-1]

(Really the same as using rpartition, I know... But piling on the possibilities is a Ruby tradition.)

Upvotes: 2

sawa
sawa

Reputation: 168249

((first, last)) = "like_this_string".scan(/(.*)_(.*)/)
first # => "like_this"
last  # => "string"

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118299

I'd do using String#rpartition

first, _, last = "like_this_string".rpartition("_")
first # => "like_this"
last # => "string"

Upvotes: 11

Related Questions