当字符串太长时截断字符串 [英] Truncate string when it is too long

查看:78
本文介绍了当字符串太长时截断字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串:

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

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

I want to change the default behavior of print to:

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

long_string 仅部分打印.我尝试更改 String#to_s,但是没有用.有人知道怎么做吗?

The long_string is only partially printed. I tried to change String#to_s, but it didn't work. Does anyone know how to do it like this?

更新

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

Actually i wanna it works smoothly, that means the following cases also work fine:

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

所以我认为该行为属于 String.

So i think the behavior belongs to String.

还是谢谢大家.

推荐答案

首先,你需要一个truncate 字符串的方法,可以是这样的:

First of all, you need a method to truncate a string, either something like:

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

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

Or by extending String: (it's not recommended to alter core classes, though)

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

现在你可以在打印字符串时调用truncate:

Now you can call truncate when printing the string:

puts "short string".truncate
#=> short string

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

或者你可以定义你自己的puts:

Or you could just define your own 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 方法.

这篇关于当字符串太长时截断字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆