2.1.1 :009 > x="
=> "
2.1.1 :010 > x+="
=> "
2.1.1 :011 >
=> 19461520
2.1.1 :012 > x+="
=> "
2.1.1 :013 >
=> 19365720
2.1.1 :014 > x="hello"
=> "hello"
2.1.1 :015 >
=> 19016160
2.1.1 :016 >
=> "
2.1.1 :017 >
=> 19016160
2.1.1 :018 >
=> "hellohi\u0002"
2.1.1 :019 >
=> 19016160
2.1.1 :020 > i=10
=> 10
Based on above exple, += always creates a new object to perform string operation and .concat work on existing object only.
2.1.1 :021 > x = "hello"
=> "hello"
2.1.1 :022 >
=> 19923680
2.1.1 :023 > x << "joy"
=> "hellojoy"
2.1.1 :024 > x.object_id
=> 19923680
2.1.1 :025 > x << "2015"
=> "hellojoy2015"
2.1.1 :026 > x.object_id
=> 19923680
<< alias for .concat
Fair question. The plus symbol, it seems, creates an intermediary copy of the variables before combining them, whereas << and concat directly concatenate the variables to each other without first producing an intermediary copy.
No comments:
Post a Comment