Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/ellipsized.rb

Overview

Replaces part of the text with a gap.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2025 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Instance Method Details

#ellipsized(max = 64, gap: '...') ⇒ String

Truncates a string to specified maximum length, inserting a gap in the middle if necessary. The resulting string will never be longer than the specified maximum length. The original string is returned if it is already shorter than or equal to the maximum length.

Examples:

Basic usage with default parameters

"Hello, world!".ellipsized
# => "Hello, world!"

Truncate a long string

"This is a very long string that needs to be truncated".ellipsized(20)
# => "This is...truncated"

Custom gap

"Another very long string example".ellipsized(15, gap: "***")
# => "Anoth***example"

Edge cases

"".ellipsized      # => ""
"Short".ellipsized # => "Short"
"xyz".ellipsized(0) # => ""
"xyz".ellipsized(2, gap: "...") # => "xy"

Parameters:

  • max (Integer) (defaults to: 64)

    The maximum length of the resulting string

  • gap (String) (defaults to: '...')

    The string to use as gap (default: ‘…’)

Returns:

  • (String)

    The truncated string with gap in the middle if necessary



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ellipsized.rb', line 38

def ellipsized(max = 64, gap: '...')
  raise "Max length must be an Integer, while #{max.class.name} provided" unless max.is_a?(Integer)
  raise "Max length (#{max}) is negative" if max.negative?
  return '' if empty?
  return self if length <= max
  return '' if max.zero?
  raise "The gap doesn't implement to_s()" unless gap.respond_to?(:to_s)

  gap = gap.to_s
  return self[0..max - 1] if gap.length >= max

  head = tail = (max - gap.length) / 2
  head += 1 if head + tail + gap.length < max
  head = max if head > max
  "#{self[0, head]}#{gap}#{self[length - tail..]}"
end