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.
string = "Good"
string.concat(" morning")
#=> "Good morning"
array = ['a', 'b', 'c']
array.concat(['d'])
#=> ["a", "b", "c", "d"]
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)
In Ruby 2.4, we can pass multiple arguments and Ruby processes each argument one by one.
string = "Good"
string.concat(" morning", " to", " you")
#=> "Good morning to you"
array = ['a', 'b']
array.concat(['c'], ['d'])
#=> ["a", "b", "c", "d"]
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"
concat
and shovel <<
operatorThough 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.
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.
If this blog was helpful, check out our full blog archive.