Method: String#squash
- Defined in:
- lib/ruby_core_extensions/string.rb
#squash(limit) ⇒ Object
Squash will reduce words from the end of the string to 3 characters until it fits within the limit, shrinking all words evenly. Where not all words can be shrunk evenly, the last words will be reduced by 1 Until within the limit e.g. “Adelaide University”.squash(30)
> “Adelaide University”
“Adelaide University”.squash(10)
> “Adela Univ”
“Adelaide University”.squash(7)
> “Ade Uni”
“Adelaide University”.squash(3)
> “AU”
“Adelaide University”.squash(2)
> “AU”
“Adelaide University”.squash(1)
> “A”
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/ruby_core_extensions/string.rb', line 39 def squash(limit) return self if size <= limit words = split(' ') # Return first letter of <limit> words return words.first(limit).map { |w| w.chars.first }.join if (words.size * 2 - 1) >= limit spaces = words.size - 1 word_char_min = (limit - spaces) / words.size word_char_max = word_char_min + 1 words = words.map { |word| word[0..(word_char_max - 1)] } words.reverse.each.with_index do |word, index| letters_to_remove = words.join(' ').size - limit letters_to_keep = if (last_case = (letters_to_remove <= (word.size - word_char_min))) word.size - letters_to_remove # Removing final characters else word_char_min end # Replace word words[words.size - index - 1] = word[0..(letters_to_keep - 1)] break if last_case end words.join(' ') end |