Eric
Eric

Reputation: 1245

How to take a substring from the beginning of a string up to the last occurrence of a character that is before a specific index in the string in Ruby

The title might be confusing. Just say I have a newspaper article. I want to cut it off around a certain point, say 4096 characters, but not in the middle of a word, rather before the last word that takes the length over 4096. Here is a short example:

"This is the entire article."

If I want to cut it off before a word that takes the total length over 16 characters, here is the result I would want:

"This is the entire article.".function
=> "This is the"

The word "entire" takes the total length over 16, so it must be removed, along with all characters after it, and the space before it.

Here is what I don't want:

"This is the entire article."[0,15]
=> "This is the ent"

It looks easy in writing, but I don't know how to put it into programming.

Upvotes: 1

Views: 2061

Answers (2)

Holger Just
Holger Just

Reputation: 55758

While the answer of marco is correct for a plain ruby, there is a simpler variant if you happen to use rails, as it already includes a truncate helper (which in turn uses the truncate method added to the String class by ActiveSupport):

text = "This is the entire article."
truncate(text, :length => 16, :separator => ' ')
# or equivalently
text.truncate(16, :separator => ' ')

Upvotes: 1

maro
maro

Reputation: 1506

How about something like this for your example:

sentence = "This is the entire article."
length_limit = 16
last_space = sentence.rindex(' ', length_limit) # => 11
shortened_sentence = sentence[0...last_space]   # => "This is the"

Upvotes: 5

Related Questions