In Ruby, when the *
operator is used with a string on the left hand side and an integer on the right hand side (i.e. string * integer
), it repeats the string as many times as specified by the integer. For example:
foo = "quack!" * 3 puts foo #=> "quack!quack!quack!"
If you want to, for example add spaces between each repeated word, then you can do so in the following way:
arr = ["quack!"] * 3 str = arr * " " puts str #=> "quack! quack! quack!"
You can shorten this into a one-liner like so:
foo = ["quack!"] * 3 * " " puts foo #=> "quack! quack! quack!"
In the first part (i.e. array * integer
), the array containing the word "quack!"
is repeated three times (as specified by the integer after the *
operator):
["quack!"] * 3 #=> [ "quack!", "quack!", "quack!" ]
Once that operation is complete, in the second part (i.e. array * string
) all the array elements are joined into a single string, separated by the value that's specified within the string to the right of the *
operator:
["quack!", "quack!", "quack!"] * " " #=> "quack! quack! quack!"
array * string
is a shorthand for using array.join(string)
. You can write the same code using array.join()
like so:
arr = ["quack!"] * 3 str = arr.join(" ") puts str #=> "quack! quack! quack!"
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.