ruby - using each and map to modify a range of an array indices -


the following code:

a = [1,2,3,4,5] b = a.each.map {|i| = 0}  # or   b = a.map {|i| = 0}  same thing 

makes b = [0, 0, 0, 0, 0] expected

is there equally succinct way change range of a? (ex: set a[2..4] 0)

i have messed around in irb, code returns elements modified

a = [1,2,3,4,5] b = a[2..4].each.map {|i| = 0} 

makes b = [0, 0, 0], trying make b = [1, 2, 0, 0, 0]

i'm not sure trying here.

first: why turning array enumerator , map enumerator instead of mapping array directly? i.e. why have

b = a.each.map {|i| = 0 } 

instead of

b = a.map {|i| = 0 } 

also, why assigning block local variable i never using variable? i.e. why don't

b = a.map {|i| 0 } 

of course, aren't using i at all ...

b = a.map { 0 } 

however, since values of b have absolutely no relationship @ values of a, might

b = [0] * a.size 

the same questions apply second code example. again, ignore elements of a, using map makes no sense whatsoever. can

(b = a.dup)[2..4] = [0] * 3 

or more readable broken 2 expressions

b = a.dup b[2..4] = [0] * 3 # or ... = [0, 0, 0] 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -