Truncate string when it is too long

后端 未结 4 550
暖寄归人
暖寄归人 2021-01-04 12:06

I have two strings:

short_string = \"hello world\"
long_string = \"this is a very long long long .... string\" # suppose more than 10000 chars
4条回答
  •  北海茫月
    2021-01-04 12:31

    This is how Ruby on Rails does it in their String#truncate method as a monkey-patch:

    class String
      def truncate(truncate_at, options = {})
        return dup unless length > truncate_at
    
        options[:omission] ||= '...'
        length_with_room_for_omission = truncate_at - options[:omission].length
        stop = if options[:separator]
          rindex(options[:separator], length_with_room_for_omission) || 
            length_with_room_for_omission
          else
            length_with_room_for_omission
          end
    
        "#{self[0...stop]}#{options[:omission]}"
      end
    end
    

    Then you can use it like this

    'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
    # => "And they f... (continued)"
    

提交回复
热议问题