Ruby 2.5 introduces
Array#append as an alias for
Likewise, there should be
String#append as an alias for
concat. The documentation for
<< even says "append":
Append—Concatenates the given object to str. [...]
String already has a
Updated by shevegen (Robert A. Heiler) over 3 years ago
I +1 agree with Stefan for symmetry. :)
However had, I may be biased since I discussed in favour of the
Array-methods .prepend() and .append() so it may be best if others
can comment here too, to avoid "mono-view bias". :)
Updated by phluid61 (Matthew Kerwin) over 3 years ago
I am opposed to this alias as proposed.
<<is known to be "dangerous", but other "safe" concatenation operations exist for String (e.g.
+). I would expect that a new word-based name for the dangerous operation would end with "
concat) casts integers as codepoints.
prependrequires that all arguments are Stringy (c.f.
+). A method named to look like
prepend, but that behaves like
concat, is confusing.
<<only accepts a single argument, but
concataccepts many, so this alias would introduce confusion about which method (concat vs. append) has what arity.
If the proposal were about adding new functionality I think it would be worth considering, but I'm against adding a new name for the sake of it.
Updated by sos4nt (Stefan Schüßler) over 3 years ago
phluid61 (Matthew Kerwin) wrote:
1 [...] I would expect that a new word-based name for the dangerous operation would end with "!".
Array#prepend. And since
String#prepend also modifies the receiver, I would expect
String#append to work in a similar way.
(Off topic but IMO,
String#concat is the one that should return a new string, just like the documentation for
String#+ says: "Concatenation—Returns a new String containing other_str concatenated to str." But it's probably a bit late to fix that.)
2 [...] A method named to look like prepend, but that behaves like concat, is confusing.
Good point. I'm fine with string-only arguments.
append would simply invoke
rb_str_append then (is that a coincidence?).
3 [...] this alias would introduce confusion about which method (concat vs. append) has what arity.
It should of course work (arity-wise) like
Array#append, i.e. accept multiple argument. I should have said "concat", not "<<" in the question's title, or better yet not call it an alias in the first place.
To avoid any further confusion: I'm proposing a new method
String#append with the following signature:
append(other_str1, other_str2,...) → str¶
Append—Append the given strings to str.
a = "hello " a.append("world", "!") #=> "hello world!" a #=> "hello world!"
See also #concat.