views:

57

answers:

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

+2  A: 
z=''
(x-1).times do
 z+=s
end
Bragboy
+1  A: 

Pseudo code (not ruby)

if 1 < int(x) < 7  then
   z = (x-1)*s
karlcow
+7  A: 

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! "
polygenelubricants
where has ideone.com been all my life +1
Dr. Frankenstein