有没有一个方法不需要.each可以优雅地添加所有奇数/偶数索引数字.
eg. 872653627
Odd: 7 + 6 + 3 + 2 = 18
Even: 8 + 2 + 5 + 6 + 7 = 28
Run Code Online (Sandbox Code Playgroud)
number.to_s.chars.map(&:to_i). # turn string into individual numbers
partition.with_index { |_, i| i.odd? }. # separate the numbers into 2 arrays
map { |a| a.reduce(:+) } # sum each array
#=> [18, 28]
Run Code Online (Sandbox Code Playgroud)