+ 2

What am I doing wrong??

arr = ["50", "80"] #elements of the array are strings arr = arr.each {|x| x.to_i} #convert all elements of the array to int arr = arr.each do |x| x *= 255 / 100 end print arr #expected output is [127, 204] with ints in the array When I run the code, I getting ["50", "80"] with strings as elements!! What am I doing wrong??

12th May 2020, 2:23 AM
Vera
Vera - avatar
3 ответов
+ 3
Use map in place of each. Your output will then be [100, 160] Note: 255 / 100 results in 2 instead of 2.55 do to integer division
12th May 2020, 3:30 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
arr = ["50", "80"] arr = arr.map do |x| x = x.to_i * 255 / 100 end print arr This will give your desired output and do it all in 1 loop.
12th May 2020, 3:40 AM
ChaoticDawg
ChaoticDawg - avatar
0
Hello
18th May 2020, 8:17 AM
Manish K