【问题标题】:Splitting an integer in an array into individual digits in Ruby将数组中的整数拆分为Ruby中的单个数字
【发布时间】:2017-06-27 23:20:04
【问题描述】:

我正在尝试从用户那里收集输入,将该输入作为整数存储在一个数组中,然后迭代 每隔一个数字,从第二个到最后一个,然后取这些数字并将它们乘以 2。之后,我将产品的各个数字相加,但我无法将该数学结果存储为整数

这是我的代码:

# Prompt user for input

print "Number: "
array = []
card = gets.to_i
array << card


# Prompt the user until the number is valid

until card.is_a?(Integer) && card.positive? && card.to_s.length > 10
  print "Retry: "
  card = gets.to_i
  array << card
end

array = array.to_s.scan(/\d/).map(&:to_i) # split number in array by digit


i = -2 # starting the loop at second to last digit
t = ((array.length)/2).ceil # number of times to iterate through the array length & roundup
$sum = 0

t.times do #go through the array as many times as digits needed, starting 2nd to last
  $sum += ((array[i]) * 2).digits
  i -= 2
end

puts $sum

这给了我控制台错误:

Array can't be coerced into Integer (TypeError)

我还尝试获取产品的各个数字并将它们放入这样的新数组中

final_array = []

t.times do #go through the array as many times as digits needed, starting 2nd to last
  final_array << ((array[i]) * 2).digits.to_i
  i -= 2
end

但这给了我错误undefined method to_i for [2]:Array

我知道还有另一种方法可以使用 % 来解决此问题,但我正在尝试使用数组来解决此问题。希望有人能帮忙!

【问题讨论】:

  • 试试这个:final_array += ((array[i]) * 2).digits
  • @OthmaneElKesri 非常感谢,成功了

标签: arrays ruby


【解决方案1】:

改变这一行:

final_array << ((array[i]) * 2).digits.to_i

通过这个:

final_array += ((array[i]) * 2).digits

【讨论】:

    【解决方案2】:

    您可以使用迭代器和数组切片来做到这一点。

    首先将数组从最后一个 (-1) 元素中去掉一个切片 (ruby array slice method),然后反转该切片。

     a = [1,2,3,4,5]
     b = a.reverse[1..-1]
      => [4, 3, 2, 1]
    

    接下来,您只需要新数组的偶数索引元素,您可以通过遍历数组并检查它的索引是否为偶数来找到它。 each_with_index 方法将帮助您解决此问题 (Ruby enumerable each_with_index method)。如果索引是偶数,则将该索引处的值存储在另一个数组中

     c = []
     b.each_with_index {|n,i| c << n if i.even? }
     c
      => [4, 2]
    

    然后使用数组inject 方法进行数学运算(这里很好解释 - SO discussion of Ruby inject)。

     c.inject(0) {|sum, n| sum + (n * 2) }
      => 12
    

    这种方法可以让您跳过对计数器变量的干扰,并在数组上反向工作,而只使用 Ruby 迭代器。

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 2021-07-16
      • 2016-12-22
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      相关资源
      最近更新 更多