Truncate string with Rails?

前端 未结 7 764
醉酒成梦
醉酒成梦 2021-01-31 07:40

I want to truncate a string as follows:

input:

string = \"abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffddd\"
7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-31 07:42

    This is the source code of String#truncate

    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
    

    So, as for you case

    string.truncate(37, :omission => "...ffffffffd")
    

提交回复
热议问题