计算Ruby数组中的Fixnums

时间:2014-03-04 10:57:21

标签: ruby arrays

我有一个具有任意数量参数的函数。我的功能如下:

sum(n, *rest)

如何遍历数组rest,以便检查参数是否为Fixnum,如果是,请加总,否则不执行任何操作?例如:

sum(5,1,2,k,D,3)
# => 6

2 个答案:

答案 0 :(得分:6)

执行以下操作:

ary = rest.grep(Fixnum)
# return the summation of the array elements, if array is not empty
# 0, when array is empty or contains only one element as `0`.
ary.reduce(0,:+) 

查看#reducegrep

示例:

ary = [1,"2",{1 => 2 },8]
ary.grep(Fixnum).inject(0,:+) # => 9
ary = ["2",{1 => 2 },(1..2)]
ary.grep(Fixnum).inject(0,:+) # => 0

# counting the how many Fixnums are there
ary = [1,"2",{1 => 2 },8]
ary.grep(Fixnum).size # => 2

答案 1 :(得分:2)

另一种方式(虽然我更喜欢@ Arup使用grep):

a.group_by(&:class)[Fixnum].reduce(0,:+)

a = [1, :cat, 3, 'dog']
b = a.group_by(&:class) #=> {Fixnum=>[1,3],Symbol=>[:cat],String=>["dog"]}
c = b[Fixnum]           #=> [1,3]       
reduce(0,:+)            #=> 4

如果数组不包含Fixnums,我假设返回零。如果在这种情况下要返回nil,请将reduce(0,:+)更改为reduce(:+)