Friday, December 19, 2014

Middle Truncate in Ruby

Here's a way to truncate the middle of a String, shortening it to the desired length, in Ruby:

class String
  def middle_truncate(len)
    return self if len >= size
    return self[0...len] unless len > 4
    half = len / 2.0
    (result = dup)[(half - 1.5).floor...(1.5 - half).floor] = '...'
    result
  end
end

This has the added benefit of just truncating if string size < 5.


e.g. for an even-sized string:

    2.1.1 :001 > s = "12345678901234567890"
     => "12345678901234567890" 
    2.1.1 :002 > s.middle_truncate 21
     => "12345678901234567890" 
    2.1.1 :003 > s.middle_truncate 20
     => "12345678901234567890" 
    2.1.1 :004 > s.middle_truncate 19
     => "12345678...34567890" 
    2.1.1 :005 > s.middle_truncate 18
     => "1234567...34567890" 
    2.1.1 :006 > s.middle_truncate 5
     => "1...0" 
    2.1.1 :007 > s.middle_truncate 4
     => "1234" 

and for an odd-sized string:

    2.1.1 :012 > s = "123456789012345678901"
     => "123456789012345678901" 
    2.1.1 :013 > s.middle_truncate 22
     => "123456789012345678901" 
    2.1.1 :014 > s.middle_truncate 21
     => "123456789012345678901" 
    2.1.1 :015 > s.middle_truncate 20
     => "12345678...345678901" 
    2.1.1 :016 > s.middle_truncate 19
     => "12345678...45678901" 
    2.1.1 :017 > s.middle_truncate 5
     => "1...1" 
    2.1.1 :018 > s.middle_truncate 4
     => "1234" 

Shared on StackOverflow

No comments: