String#concat, Array#concat & String#prepend Ruby 2.4

Abhishek Jain

By Abhishek Jain

on October 28, 2016

This blog is part of our  Ruby 2.4 series.

In Ruby, we use #concat to append a string to another string or an element to the array. We can also use #prepend to add a string at the beginning of a string.

Ruby 2.3

String#concat and Array#concat

1
2string = "Good"
3string.concat(" morning")
4#=> "Good morning"
5
6array = ['a', 'b', 'c']
7array.concat(['d'])
8#=> ["a", "b", "c", "d"]
9

String#prepend

1
2string = "Morning"
3string.prepend("Good ")
4#=> "Good morning"
5

Before Ruby 2.4, we could pass only one argument to these methods. So we could not add multiple items in one shot.

1
2string = "Good"
3string.concat(" morning", " to", " you")
4#=> ArgumentError: wrong number of arguments (given 3, expected 1)
5

Changes with Ruby 2.4

In Ruby 2.4, we can pass multiple arguments and Ruby processes each argument one by one.

String#concat and Array#concat

1
2string = "Good"
3string.concat(" morning", " to", " you")
4#=> "Good morning to you"
5
6array = ['a', 'b']
7array.concat(['c'], ['d'])
8#=> ["a", "b", "c", "d"]
9

String#prepend

1
2string = "you"
3string.prepend("Good ", "morning ", "to ")
4#=> "Good morning to you"
5

These methods work even when no argument is passed unlike in previous versions of Ruby.

1
2"Good".concat
3#=> "Good"
4

Difference between concat and shovel << operator

Though shovel << operator can be used interchangeably with concat when we are calling it once, there is a difference in the behavior when calling it multiple times.

1
2str = "Ruby"
3str << str
4str
5#=> "RubyRuby"
6
7str = "Ruby"
8str.concat str
9str
10#=> "RubyRuby"
11
12str = "Ruby"
13str << str << str
14#=> "RubyRubyRubyRuby"
15
16str = "Ruby"
17str.concat str, str
18str
19#=> "RubyRubyRuby"
20

So concat behaves as appending present content to the caller twice. Whereas calling << twice is just sequence of binary operations. So the argument for the second call is output of the first << operation.

If you liked this blog, you might also like the other blogs we have written. Check out the full archive.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, React.js, React Native, remote work,open source, engineering & design.