Truncate string when it is too long

后端 未结 4 585
暖寄归人
暖寄归人 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:24

    Truncate naturally

    I want to propose a solution that truncates naturally. I fell in love with the String#truncate method offered by Ruby on Rails. It was already mentioned by @Oto Brglez above. Unfortunately I couldn't rewrite it for pure ruby. So I wrote this function.

    def truncate(content, max)    
        if content.length > max
            truncated = ""
            collector = ""
            content = content.split(" ")
            content.each do |word|
                word = word + " " 
                collector << word
                truncated << word if collector.length < max
            end
            truncated = truncated.strip.chomp(",").concat("...")
        else
            truncated = content
        end
        return truncated
    end
    

    Example

    • Test: I am a sample phrase to show the result of this function.
    • NOT: I am a sample phrase to show the result of th...
    • BUT: I am a sample phrase to show the result of...

    Note: I'm open for improvements because I'm convinced that there is a shorter solution possible.

提交回复
热议问题