本文介绍了ruby - 简化字符串乘法连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
s 是一个字符串,这看起来很啰嗦——我该如何简化它?:
如果 x === 2z = selif x === 3z = s+selif x === 4z = s+s+selif x === 5z = s+s+s+selif x === 6z = s+s+s+s+s
谢谢
解决方案
这样的事情是最简单且有效的 (如上所见ideone.com):
puts 'Hello' * 3 # HelloHelloHellos = '去'x = 4z = s * (x - 1)puts z # GoGoGo
API 链接
ruby-doc.org - String
: str * integer =>new_str
Copy — 返回一个新的 String
,其中包含接收者的整数 个副本.
"嗨!"* 3 #=>"呵!呵!呵!"
s is a string, This seems very long-winded - how can i simplify this? :
if x === 2
z = s
elsif x === 3
z = s+s
elsif x === 4
z = s+s+s
elsif x === 5
z = s+s+s+s
elsif x === 6
z = s+s+s+s+s
Thanks
解决方案
Something like this is the simplest and works (as seen on ideone.com):
puts 'Hello' * 3 # HelloHelloHello
s = 'Go'
x = 4
z = s * (x - 1)
puts z # GoGoGo
API links
这篇关于ruby - 简化字符串乘法连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!