Skip to content

Instantly share code, notes, and snippets.

@headquarters
Last active September 6, 2015 06:34
Show Gist options
  • Save headquarters/96bbc01de997b9885e85 to your computer and use it in GitHub Desktop.
Save headquarters/96bbc01de997b9885e85 to your computer and use it in GitHub Desktop.
Prevent widows in Ruby with this simple function. It replaces only the last space character with a non-breaking space in a string.
def prevent_widows(text)
if text.kind_of? String
trimmed_text = text.rstrip
last_space_index = trimmed_text.rindex(" ")
if !last_space_index.nil?
text[last_space_index] = " "
end
end
text
end
@headquarters
Copy link
Author

I guess it would be more appropriately called "prevent orphans", since it's concerned with the last word not being on a line by itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment