红宝石:如何任一个变量设置为0,或者,如果它已被设置,递增1 [英] Ruby: How to either set a variable to 0 or, if it is already set, increment by 1

查看:62
本文介绍了红宝石:如何任一个变量设置为0,或者,如果它已被设置,递增1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道|| =操作,但不认为这会帮助我在这里...试图创建计算对象的数组中类型的数量的数组。

  array.each做| C |
  newarray [c.type] = newarray [c.type] newarray [c.type] +1? 0
结束

有没有更优雅的方式来做到这一点?


解决方案

  =类型Hash.new(-1)#这感觉就像这应该是0,但要
                     #等同于你的榜样,它必须是-1
array.each做| C |
  类型[c.type] + = 1
结束

I know of the ||= operator, but don't think it'll help me here...trying to create an array that counts the number of "types" among an array of objects.

array.each do |c|
  newarray[c.type] = newarray[c.type] ? newarray[c.type]+1 ? 0
end

Is there a more graceful way to do this?

解决方案

types = Hash.new(-1) # It feels like this should be 0, but to be
                     # equivalent to your example it needs to be -1
array.each do |c|
  types[c.type] += 1
end

这篇关于红宝石:如何任一个变量设置为0,或者,如果它已被设置,递增1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆