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
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 << .
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.
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.
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."
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
ruby-doc.org -
String
:str * integer => new_str
Copy—Returns a new
String
containing integer copies of the receiver."Ho! " * 3 #=> "Ho! Ho! Ho! "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With