Yuval Karmi
Yuval Karmi

Reputation: 26713

How to slice off a string in Ruby using another string?

Say I have a sentence similar to the following:

The quick brown fox jumps over the lazy dog

I'd like to slice off everything before and including "jumps", so I am left with:

 over the lazy dog

Currently, I get the index of the part I'd like to remove, then add the length of that part to it, and then slice it, as such:

sentence = "The quick brown fox jumps over the lazy dog"
slice_index = sentence.index("jumps").to_i + sentence.size
sliced_sentence = sentence.slice(slice_index..-1)

Is there a better way of achieving this?

Thanks!

Upvotes: 2

Views: 4247

Answers (3)

Kyle Heironimus
Kyle Heironimus

Reputation: 8041

Personally, I like the regex solution, but

sentence.split(" jumps ").last

works too, even if there are multiple "jumps".

Upvotes: 5

user644666
user644666

Reputation: 33

Perhaps not the best solution but I would do it like so:

sentence = "The quick brown fox jumps over the lazy dog"
sentence.split(" jumps ")[1]

split divides str into substrings based on a delimiter, returning an array of these substrings. array index 1 will always be the section after the delimiter. This breaks if there are more than one " jumps "

Upvotes: 1

Matt
Matt

Reputation: 17629

You could use a regular expression:

sentence =~ /jumps(.*)$/
sliced_sentence = $1
#=> " over the lazy dog"

jump is the word you are looking for, (.*)$ is everything until the end of the string and the brackets represent the first capturing group (which is therefore referenced as $1)

Upvotes: 3

Related Questions