在一行中递归求和值

时间:2017-12-08 18:16:35

标签: ruby

我很确定它可以使用地图,总和等等在一行中完成。我无法弄清楚究竟是多少,因为我刚开始学习红宝石。有人可以帮忙吗?感谢

 class Something < ApplicationRecord
 def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end

3 个答案:

答案 0 :(得分:0)

我不确定为什么你需要递归地在一行中做,但你可以尝试这样的事情:

修改

def add(arr)
    return 0 if arr.length == 0
    # if the arr argument is an empty array, return 0.

    arr[0] + add(arr[1..-1])
    # add the first element of the array to the result of calling add
    # on the array minus the first element.
end

如果您只想尽可能简洁地对数组求和,那么您需要做的只是[1, 2, 3].sum[1,2,3,4].reduce(&:+)。不需要递归。

答案 1 :(得分:0)

直截了当的oneliner等同于你的:

  def function
    items.count + items.sum(&:function)
  end

演示(与原版一起测试):

class Something
  attr_accessor :items

  def initialize(items = [])
    self.items = items
  end

  def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end

  def function2
    items.count + items.sum(&:function2)
  end
end

root = Something.new([
         Something.new,
         Something.new([
           Something.new,
           Something.new([
             Something.new,
             Something.new([
               Something.new
             ])
           ])
         ])
       ])

puts root.function
puts root.function2

打印:

7
7

另一种方式:

  def function
    items.sum { |i| 1 + i.function }
  end

顺便说一句,您计算除根项目以外的所有项目。这是故意的吗? 你可以用这个计算所有包括根的所有内容:

  def function
    1 + items.sum(&:function)
  end

答案 2 :(得分:0)

不在一行中,但这是递归执行此操作的方法。

def add_array(arr)
 return arr.first if arr.length == 1 
 return nil if arr.length < 1
 
 arr.pop + add_arr(arr)
end