开发者

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

开发者 https://www.devze.com 2023-03-16 15:26 出处:网络
The following code: a = [1,2,3,4,5] b = a.each.map {|i| i = 0}# orb = a.map {|i| i = 0}does the same thing

The following code:

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

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

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

I have messed around in irb, but my code returns only the elements that were modifi开发者_运维问答ed

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

makes b = [0, 0, 0], where as I am trying to make b = [1, 2, 0, 0, 0]


I'm not exactly sure what you are trying to do here.

First: why are you turning the Array into an Enumerator and then map that Enumerator instead of just mapping the Array directly? I.e. why do you have

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

instead of just

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

Also, why are you assigning to the block local variable i but never actually using that variable? I.e. why don't you just do

b = a.map {|i| 0 }

Of course, now you aren't using i at all ...

b = a.map { 0 }

However, since the values of b actually have absolutely no relationship at all to the values of a, you might just as well do

b = [0] * a.size

The same questions basically apply also to your second code example. Again, you completely ignore the elements of a, so using map simply makes no sense whatsoever. You can just do

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

Or slightly more readable broken up into two expressions

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号