这只是我想到的一个随机场景,如果我有这个阵列:
[3,2,5,6,7,8,9,1,2]
和这个字符串:
'325678912'
我会使用Ruby编写哪些代码来生成:
3*2*5 = 30, 6*7*8 = 336, and 9*1*2 = 18
并将其放入以下数组:
[30,336,18]
抱歉,我忘了把我的代码放回错误的答案:
b = [3,2,5,6,7,8,9,1,2]
first = 0
third = first + 2
array = []
while first<b.length
prod=1
b[first..third].each do |x|
prod*=x.to_i
array<<prod
end
first+=2
third = first + 2
end
print array
我的另一段代码:
a = '325678912'
number = a.split('')
first = 0
third = first + 2
array = []
while first<number.length
prod=1
number[first..third].each do |x|
prod*=x.to_i
array<<prod
end
first+=2
third = first + 2
end
print array
对于这两段代码,我得到了这个答案:[3,6,30,5,30,210,7,56,504,9,9,18,2],我想要的是:[30,336, 18]
有谁能告诉我我的代码有什么问题?
提前谢谢!
答案 0 :(得分:5)
[3,2,5,6,7,8,9,1,2].each_slice(3).map { |a,b,c| a*b*c }
# => [30, 336, 18]
[3,2,5,6,7,8,9,1,2].each_slice(3).map { |x| x.reduce(:*) }
# => [30, 336, 18]
使用String#chars
将字符串转换为单字符串数组。然后使用上面的代码来获得结果:
'325678912'.chars
# => ["3", "2", "5", "6", "7", "8", "9", "1", "2"]
'325678912'.chars.map(&:to_i)
# => [3, 2, 5, 6, 7, 8, 9, 1, 2]
'325678912'.chars.map(&:to_i).each_slice(3).map { |a,b,c| a*b*c }
# => [30, 336, 18]
答案 1 :(得分:1)
您的代码,带有评论。
b = [3,2,5,6,7,8,9,1,2]
first = 0
third = first + 2
array = []
while first<b.length
prod=1
b[first..third].each do |x|
prod*=x.to_i # to_i unnecessary, already integer
array<<prod # Ah no. Too early. move this outside the block
end
#Here would be fine.
#And don't forget to reset prod to 1.
first+=2 #3 ! not 2.
third = first + 2
end
print array