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
string = "Good"
string.concat(" morning")
#=> "Good morning"
array = ['a', 'b', 'c']
array.concat(['d'])
#=> ["a", "b", "c", "d"]
String#prepend
string = "Morning"
string.prepend("Good ")
#=> "Good morning"
Before Ruby 2.4, we could pass only one argument to these methods. So we could not add multiple items in one shot.
string = "Good"
string.concat(" morning", " to", " you")
#=> ArgumentError: wrong number of arguments (given 3, expected 1)
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
string = "Good"
string.concat(" morning", " to", " you")
#=> "Good morning to you"
array = ['a', 'b']
array.concat(['c'], ['d'])
#=> ["a", "b", "c", "d"]
String#prepend
string = "you"
string.prepend("Good ", "morning ", "to ")
#=> "Good morning to you"
These methods work even when no argument is passed unlike in previous versions of Ruby.
"Good".concat
#=> "Good"
Difference between concat
and shovel <<
operator
Though shovel <<
operator can be used interchangably with
concat
when we are calling it once, there is a difference
in the behavior when calling it multiple times.
str = "Ruby"
str << str
str
#=> "RubyRuby"
str = "Ruby"
str.concat str
str
#=> "RubyRuby"
str = "Ruby"
str << str << str
#=> "RubyRubyRubyRuby"
str = "Ruby"
str.concat str, str
str
#=> "RubyRubyRuby"
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.