【问题标题】:Trying to get the previous and next item of an array using index尝试使用索引获取数组的上一项和下一项
【发布时间】:2020-10-09 03:43:13
【问题描述】:

我要做的是创建一个新数组,它从输入数组中迭代并遍历它。新数组的每一项都是迭代前一项和下一项相乘的结果。

例如:

Array input: [1, 2, 3, 4, 5, 6]
Array_final: [2, 3, 8, 15, 24, 30]
   first item: 2*1 (because there's no previous item)
   second item: 3*1
   third item: 4*2
   forth item: 5*3
   fifth item: 6*4
   sixth item: 6*5 (we use the current item because we don't have a next one)

这是我的代码,我不明白为什么我不断得到 array_final = [0, 0, 0, 0, 0, 0]

class Arrays
      def self.multply(array)
        array_final = []
        last_index = array.length-1
      
        array.each_with_index do |num, i|
          if i == 0
            array_final.push (num[i+1])
          elsif i == last_index
            array_final.push (num*num[i-1])
          else
            array_final.push(num[i+1]*num[i-1])
          end
        end
        return array_final
      end
    end

【问题讨论】:

    标签: arrays ruby indexing each


    【解决方案1】:

    当它是一个元素时,您将 num 用作数组。

    我想你的意思是:

    array.each_with_index do |num, i|
      if i == 0
        array_final.push (array[i+1])
      elsif i == last_index
        array_final.push (num*array[i-1])
      else
        array_final.push(array[i+1]*array[i-1])
      end
    end
    

    【讨论】:

    • @KhaledJorbran:你的解释当然是对的,但为什么 Integer (num[i+1]) 的索引不是一个错误?事实上,我在 irb 中尝试过它,并且 i.. 1[1] 被排除在外并返回 0。不过,Ruby docs 不显示数字的 [] 方法的存在。
    • @user1934428 它存在Integer 类,显然它返回该索引的位值,检查它here。感谢您的好奇心.. 我们学到了一些东西!
    【解决方案2】:

    您可以使用each_cons 获取顺序项:

    final = [input[0] * input[1]]
    
    input.each_cons(3) do |precedent, _current, subsequent|
      final << precedent * subsequent
    end
    
    final << input[-1] * input[-2]
    

    Live example

    【讨论】:

    • 或者,删除 final = ...final &lt;&lt;.. 并写入 [1,*input,1].each_cons(3) do |precedent, _current, subsequent|; final &lt;&lt; precedent * subsequent; end
    猜你喜欢
    • 1970-01-01
    • 2012-02-04
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多