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 = '...', align = :center) ⇒ 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, '***')
# => "Anoth***example"

Custom align

"Another very long string example".ellipsized(15, '...', :left)
# => "...tring example"

Edge cases

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

Parameters:

  • max (Integer) (defaults to: 64)

    The maximum length of the resulting string

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

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

  • align (Symbol) (defaults to: :center)

    The alignment can be :left, :center, or :right (default: :center)

Returns:

  • (String)

    The truncated string with gap in the middle if necessary



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ellipsized.rb', line 44

def ellipsized(max = 64, gap = '...', align = :center)
  validate_arguments(max, gap, align)
  return '' if empty?
  return self if length <= max
  return '' if max.zero?

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

  case align
  when :left
    "#{gap}#{self[length - max + gap.length..]}"
  when :center
    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..]}"
  when :right
    "#{self[0, max - gap.length]}#{gap}"
  end
end