DEV Community

Rossella Ferrandino
Rossella Ferrandino

Posted on

1 2

Learning Ruby: string concatenation

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay