ruby - Some misunderstanding using Array#map method -
let's have following block of code:
arr = ['a','b','c'] arr.map {|item| item <<'1'} #=> ['a1','b1','c1'] arr #=> ['a1','b1','c1']
why array#map
change array? should create new one. when i'm using +
in block instead of <<
, works expected. array#each
change array itself, or iterate on , return itself?
my question is: why
map
change array? should create new.
map
doesn't change array
. <<
changes string
s in array
.
see the documentation string#<<
:
str << obj → str
append—concatenates given object
str
.
although isn't mentioned explicitly, code example shows <<
mutates receiver:
a = "hello " << "world" #=> "hello world" a.concat(33) #=> "hello world!"
it's strange, because when i'm using
+
operator in block insted of<<
works expected.
+
doesn't change string
s in array
.
see the documentation string#+
:
str + other_str → new_str
concatenation—returns new
string
containingother_str
concatenatedstr
.
note how says "new string
" , return value given new_str
.
and second question:
array#each
change array or iterate on array , return itself?
array#each
not change array
. of course, block passed array#each
may or may not change individual elements of array
:
arr = %w[a b c] arr.map(&:object_id) #=> array of 3 large numbers arr.each {|item| item <<'1' } #=> ['a1', 'b1', 'c1'] arr.map(&:object_id) #=> array of same 3 large numbers
as can see, array#each
did not change array
: still same array
same 3 elements.
Comments
Post a Comment