Class: String
- Inherits:
-
Object
- Object
- String
- 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
-
#ellipsized(max = 64, gap = '...', align = :center) ⇒ String
Truncates a string to specified maximum length, inserting a gap in the middle if necessary.
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.
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 |