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 strings 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 strings in array.

see the documentation string#+:

str + other_str → new_str 

concatenation—returns new string containing other_str concatenated str.

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

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -