ruby - Difference between += for Integers/Strings and << For Arrays? -
i'm confused different results i'm getting when performing simple addition/concatenation on integers, strings , arrays in ruby. under impression when assigning variable b (see below), , changing value of a, b remain same. , in first 2 examples. when modify array in 3rd example, both , b modified.
a = 100 b = a+= 5 puts puts b
a = 'abcd' b = a += 'e' puts puts b
a = [1,2,3,4] b = a << 5 puts a.inspect puts b.inspect
the following returned in terminal above code:
ricks-macbook-pro:programs rickthomas$ ruby variablework.rb 105 100 abcde abcd [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] ricks-macbook-pro:programs rickthomas$
i given following explanation programming instructor:
assigning new variable giving additional label, doesn't make copy.
it looks += method, <<, , you'd expect behave similarly. in reality, it's "syntactic sugar", added language make things easier on developers.
when run += 1, ruby converts = + 1.
in case, we're not modifying fixnum in a. instead, we're re-assigning on top of it, blowing away previous value of a.
on other hand, when run b << "c", you're modifying underlying array appending string "c" it.
my questions these:
1) mentions syntactic sugar, isn't << is, i.e. syntactic sugar .push method?
2) why matter if += syntactic sugar or more formal method? if there difference between two, doesn't mean previously-understood of syntactic sugar ("syntax within programming language designed make things easier read or express") incomplete, since isn't purpose?
3) if assigning b doesn't make copy of a, why doesn't wiping away a's old value mean b's old value wiped away 3 cases (integer, string , array)?
as can see, i'm pretty turned around on thought understood until now. appreciated!
you see, names (variable names, a
, b
) don't hold values themselves. point value. when make assignment
a = 5
then a
points value 5, regardless of pointed previously. important.
a = 'abcd' b =
here both a
, b
point same string. but, when this
a += 'e'
it's translated to
a = + 'e' # = 'abcd' + 'e'
so, name a
bound new value, while b
keeps pointing "abcd".
a = [1,2,3,4] b = a << 5
there's no assignment here, method <<
modifies existing array without replacing it. because there's no replacement, both a
, b
still point same array , 1 can see changes made another.
Comments
Post a Comment