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: '...') ⇒ String
Truncates a string to specified maximum length, inserting a gap in the middle if necessary.
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.
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 |