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 ).
For example:
solution("1", "22") # returns "1221"
solution("22", "1") # returns "1221"
At first, I tried using the concat
method, similarly to what I would do in JavaScript. I was surprised when the output of my function was:
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 concat
.
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"
Summary
In Ruby, there are various ways to concatenate two or more strings:
+ operator
Strings can be appended to one another using the + operator, like in JavaScript and other languages. This will not modify the initial string.
concat method
This method will change the string instead of creating a new one.
<< method
This is an alias for concat and it also mutates the initial string.
Top comments (0)