当字符串太长时截断字符串

我有两个字符串:

short_string = "hello world" long_string = "this is a very long long long .... string" # suppose more than 10000 chars 

我想将print的默认行为更改为:

 puts short_string # => "hello world" puts long_string # => "this is a very long long....." 

long_string仅部分打印。 我试图改变String#to_s ,但它没有用。 有谁知道怎么做这样吗?

更新

实际上我想它运作顺利,这意味着以下情况也可以正常工作:

 > puts very_long_str > puts [very_long_str] > puts {:a => very_long_str} 

所以我认为这种行为属于String。

无论如何,谢谢大家。

首先,您需要一种方法来truncate字符串,例如:

 def truncate(string, max) string.length > max ? "#{string[0...max]}..." : string end 

或者通过扩展String :(不建议改变核心类)

 class String def truncate(max) length > max ? "#{self[0...max]}..." : self end end 

现在,您可以在打印字符串时调用truncate

 puts "short string".truncate #=> short string puts "a very, very, very, very long string".truncate #=> a very, very, very, ... 

或者您可以定义自己的puts

 def puts(string) super(string.truncate(20)) end puts "short string" #=> short string puts "a very, very, very, very long string" #=> a very, very, very, ... 

请注意, Kernel#puts采用可变数量的参数,您可能需要相应地更改puts方法。

这就是Ruby on Rails在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 

然后你可以像这样使用它

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

是的。 它添加到Rails作为猴子补丁 。 所以它实现如下:

 class String def truncate.. end end 

您可以编写一个包含处理截断的包装器:

 def pleasant(string, length = 32) raise 'Pleasant: Length should be greater than 3' unless length > 3 truncated_string = string.to_s if truncated_string.length > length truncated_string = truncated_string[0...(length - 3)] truncated_string += '...' end puts truncated_string truncated string end 

自然截断

我想提出一个自然截断的解决方案。 我爱上了Ruby on Rails提供的String#truncate方法 。 上面已经提到了@Oto Brglez。 不幸的是我无法用纯ruby重写它。 所以我写了这个函数。

 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 

  • 测试:我是一个示例短语,用于显示此function的结果。
  • 不是:我是一个示例短语来显示...的结果
  • 但是:我是一个示例短语,用于显示......的结果

注意:我愿意接受改进,因为我确信可以采用更短的解决方案。