ruby - simplify string multiply concatenation

◇◆丶佛笑我妖孽 提交于 2019-12-06 21:50:41

问题


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


回答1:


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-doc.org - String: str * integer => new_str

Copy—Returns a new String containing integer copies of the receiver.

"Ho! " * 3   #=> "Ho! Ho! Ho! "



回答2:


z=''
(x-1).times do
 z+=s
end



回答3:


Pseudo code (not ruby)

if 1 < int(x) < 7  then
   z = (x-1)*s



回答4:


For example for a rating system up to 5 stars you can use something like this:

def rating_to_star(rating)
   'star' * rating.to_i + 'empty_star' * (5 - rating.to_i)
end


来源:https://stackoverflow.com/questions/3179083/ruby-simplify-string-multiply-concatenation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!