We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
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.
1
2string = "Good"
3string.concat(" morning")
4#=> "Good morning"
5
6array = ['a', 'b', 'c']
7array.concat(['d'])
8#=> ["a", "b", "c", "d"]
9
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
In Ruby 2.4, we can pass multiple arguments and Ruby processes each argument one by one.
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
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
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.
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.