Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - simplify string multiply concatenation

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

like image 868
Dr. Frankenstein Avatar asked Jul 05 '10 11:07

Dr. Frankenstein


People also ask

How do you concatenate strings in Ruby?

Concatenating strings or string concatenation means joining two or more strings together. In Ruby, we can use the plus + operator to do this, or we can use the double less than operator << .

How do I concatenate a string and a number in Ruby?

concat is a String class method in Ruby which is used to Concatenates two objects of String. If the given object is an Integer, then it is considered a codepoint and converted to a character before concatenation.

How do you multiply in Ruby?

In Ruby, you cannot multiply strings by other strings. However, in Ruby there are type conversions. Ruby's string class offers a method of converting strings to integers. In your case, you first need to convert BOTH strings to an integer.

How do you create a string in Ruby?

Creating and Printing Strings. Strings exist within either single quotes ' or double quotes " in Ruby, so to create a string, enclose a sequence of characters in one or the other: 'This is a string in single quotes. ' "This is a string in double quotes."


1 Answers

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! "
like image 144
polygenelubricants Avatar answered Oct 06 '22 19:10

polygenelubricants