简体   繁体   English

Ruby重构哈希循环方法返回

[英]Ruby refactoring a hash loop method return

I have code like thus (and I often run into this sort of method signature, the noob that I am coming from java): 我有这样的代码(而且我经常遇到这种方法签名,即我来自Java的菜鸟):

  def totals
    t = 0
    @data.each do |k, v|
      t += v['totals'].to_i
    end
    t
  end

@data is a hash of hashes, each internal hash value has a totals key. @data是哈希的哈希,每个内部哈希值都有一个totals键。 As you can see, I am summing up all the totals. 如您所见,我正在汇总所有总数。

Could this be simplified or programmed in a different style (I am sure! This is RUBY afterall)? 是否可以简化或以其他样式编程(我确定!毕竟是RUBY)? Why do I need to instantiate t ? 为什么我需要实例化t Couldn't I return t directly from the each loop without a last conditional? 我不能在没有最后一个条件的情况下直接从每个循环中返回t吗?

It just does not feel clean! 只是感觉不干净! OH wait! 等一下! I just remembered blocks , but I'll wait for your answers ... 我只是想起了障碍 ,但我会等你的回答...

UPDATE: 更新:

The data structure is as such: 数据结构如下:

{ typeA: { items: [], totals: "10" },  typeB: { items: [], totals: "23" }}

I am using Rails! 我正在使用Rails! So Rails specific functions would also be great if they extend beyond the vanilla Ruby stack! 因此,如果Rails特定的功能超出了原始的Ruby堆栈,那么它们也将很棒!

Since you've indicated that you are using Ruby on Rails, you can take advantage of Active Support's Enumerable#sum method: 由于您已经表明您正在使用Ruby on Rails,因此可以利用Active Support的Enumerable#sum方法:

def totals
  @data.sum {|_,v| v['totals'].to_i }
end

Use inject : 使用inject

def totals
  @data.inject(0) do |t, (_, v)|
    t + v['totals'].to_i
  end
end

Use Enumerable sum 使用可数总和

def totals
  @data.sum { |_,v| v['totals'].to_i }
end

You can also have start value different from 0 您也可以将起始值设置为不同于0的值

def totals(start_value= 0)
  @data.sum(start_value) { |_,v| v['totals'].to_i }
end

在Rails 5中,您可以利用Enumerable#pluck优势

h.values.pluck(:totals).map(&:to_i).sum
@data.map{ |_, v| v['totals'].to_i }.inject(:+)

甚至更短:

@data.map{ |_, v| v['totals'].to_i }.sum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM