I have been practicing my Ruby beginner skills on Codewars this week and I just came across this interesting Kata which taught me something new about concatenating strings.
The description of the Kata is as follows:
Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside.
The strings will not be the same length, but they may be empty ( length 0 ).
solution("1", "22") # returns "1221" solution("22", "1") # returns "1221"
At first, I tried using the
def solution(a, b) puts a.length > b.length ? b.concat(a).concat(b) : a.concat(b).concat(a) end solution("a", "bb") # returns "abbabb"
As a matter of fact the
concat method in Ruby will change the initial string, and that is why the last
.concat(a) was concatenating an incorrect value. The same happens when you use the method
<<, which is equivalent to
In order to resolve the Kata, I used the + operators, which does not mutate the initial string.
def solution(a, b) puts a.length > b.length ? b + a + b : a + b + a end solution("a", "bb") # returns "abba"
In Ruby, there are various ways to concatenate two or more strings:
This method will change the string instead of creating a new one.
This is an alias for concat and it also mutates the initial string.