Allen Liu
Allen Liu

Reputation: 4038

Rails truncate helper with index and separator

Is there a method similar to the Rails truncate method that accepts an index where I can indicate the start of truncation and a separator parameter so that it does not start in the middle of a word or string?

For example:

"i love the taste of bubble tea after lunch."

I would like to grab a string of size 15 starting from index 9 so this should result in:

"the taste of bubble"

Upvotes: 0

Views: 125

Answers (1)

carols10cents
carols10cents

Reputation: 7013

I don't think there is one function to do this, so you'll have to write your own. I'd recommend chopping off the start of the string first and then using truncate to handle the end. Something like this might do what you want:

def truncate_beginning_and_end(str, beginning, length, separator)
  first_space_before_beginning = str[0..beginning].rindex(separator)
  str_without_beginning = str[(first_space_before_beginning + 1)..-1]
  truncate(str_without_beginning, length: length, separator: separator, omission: '')
end

Upvotes: 1

Related Questions