ruby - Why doesn't map! with an if work like I expect? -
when run following code:
range = [2,3,4,5,6,7,8,9,10] range.each {|z| print z, " "} puts "\n" range.map! {|y| y /= 3 if y % 3 == 0} range.each {|z| print z, " "}
i following output:
2 3 4 5 6 7 8 9 10 nil 1 nil nil 2 nil nil 3 nil
whereas i'm expecting second line of output contain:
2 1 4 5 2 7 8 3 10
what doing wrong? misunderstanding way map
operator , how associated code block supposed work?
note: i'm learning ruby after programming extensively in c/c++ number of years, , smallest snippet of non-working ruby program i've been stuck in. if required, can paste original program out of constructed mwe well.
y /= 3 if y % 3 == 0
whole expression on own. when conditional part evaluates false, entire expression evaluates nil
. map!
modifying array in-place , doesn't care if resulting elements numbers or nil
.
one way rewrite desired output be:
range.map! {|y| y % 3 == 0 ? y / 3 : y}
Comments
Post a Comment