+ 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??
4 Antworten
+ 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
+ 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.
0
Hello