Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
+= vs << when appending arrays to an array
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Robert Klemme, post: 4411681"] You should use "push" with "*" over "+=" since it is more efficient. "+=" creates a new instance before reassigning to that: "+=": irb(main):001:0> a=%w{a b c} ["a", "b", "c"] irb(main):002:0> b=[1,2,3] [1, 2, 3] irb(main):003:0> a.__id__ 22401168 irb(main):004:0> a += b ["a", "b", "c", 1, 2, 3] irb(main):005:0> a.__id__ 22388400 irb(main):006:0> "push": irb(main):011:0> a=%w{a b c} ["a", "b", "c"] irb(main):012:0> b=[1,2,3] [1, 2, 3] irb(main):013:0> a.__id__ 22192460 irb(main):014:0> a.push *b ["a", "b", "c", 1, 2, 3] irb(main):015:0> a.__id__ 22192460 irb(main):016:0> You can do it via push, but you can't with your own implementation of << since you would want to do a << *translate("foo") which isn't possible to do because it yields a syntax error. Otherwise you would have to add the logic you mentioned and do a "push *" for all Enumerables. This way you can never append an array as such with this operator other than doing: a << [[1,2,3]] which is a bit odd because of the nesting. Regards robert [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
+= vs << when appending arrays to an array
Top