1

如果我有这个数组,这只是我脑海中想到的一个随机场景:

[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]

谁能告诉我我的代码有什么问题?

先感谢您!

4

2 回答 2

5

使用Enumerable#each_slice

[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]
于 2013-10-10T14:35:06.967 回答
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
于 2013-10-10T16:16:37.307 回答