我有两个字符串:
short_string = "hello world"
long_string = "this is a very long long long .... string" # suppose more than 10000 chars
Run Code Online (Sandbox Code Playgroud)
我想将默认行为更改print为:
puts short_string
# => "hello world"
puts long_string
# => "this is a very long long....."
Run Code Online (Sandbox Code Playgroud)
的long_string仅部分打印.我试图改变String#to_s,但它没有用.有谁知道怎么做这样吗?
更新
实际上我想它运作顺利,这意味着以下情况也可以正常工作:
> puts very_long_str
> puts [very_long_str]
> puts {:a => very_long_str}
Run Code Online (Sandbox Code Playgroud)
所以我认为这种行为属于String.
无论如何,谢谢大家.
Ste*_*fan 16
首先,你需要truncate一个字符串的方法,如下所示:
def truncate(string, max)
string.length > max ? "#{string[0...max]}..." : string
end
Run Code Online (Sandbox Code Playgroud)
或者通过扩展String:(不建议改变核心类)
class String
def truncate(max)
length > max ? "#{self[0...max]}..." : self
end
end
Run Code Online (Sandbox Code Playgroud)
现在您可以truncate在打印字符串时调用:
puts "short string".truncate
#=> short string
puts "a very, very, very, very long string".truncate
#=> a very, very, very, ...
Run Code Online (Sandbox Code Playgroud)
或者您可以定义自己的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, ...
Run Code Online (Sandbox Code Playgroud)
请注意,Kernel#puts采用可变数量的参数,您可能需要相应地更改puts方法.
Oto*_*lez 11
这就是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
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它
'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
# => "And they f... (continued)"
Run Code Online (Sandbox Code Playgroud)
class String
def truncate..
end
end
Run Code Online (Sandbox Code Playgroud)