Operations on Strings!
Differences between Ruby and JavaScript.
15/12/2014
One of the first differences I found while studying JavaScript is that the only operation you can perform on strings is +, which is used for concatenating. On Ruby you can also use * to multiply the sentence or pieces of it. Like this:
i = 1 10.times do puts "*" * i i += 1 end
This will print a triangle with 10 rows in Ruby. To do the same thing on JavaScript we would need to do:
for(var i="*"; i!="***********"; i+="*"){ console.log(i); }
As you can see, on the JavaScript example I had to concatenate the new stars while on the Ruby example I just multiplied it. I could get the same result by typing 10 stars and telling the loop to keep adding * until it the row had 11 stars. This would be unviable if I wanted to make a triangle with 1000 rows.
The solution would be creating a function to do that for you. Like this one:
function repeat(string, multiplier){ var stringRepeated = []; while(stringRepeated.length < multiplier){ stringRepeated.push(string); } return stringRepeated.join(''); }
This function accepts the string to be repeated and the number of times you want to repeat it as parameters, then it creates an array which will receive the string until its length is the same as the multiplier. Then you join the all the elements in the array as one. And now we can multiply strings on JavaScript!