我有一个带有任意数量参数的函数。我的函数如下所示:
sum(n, *rest)
我如何遍历数组 rest
以便检查参数是否为 Fixnum
,如果是则求和,否则不执行任何操作?例如:
sum(5,1,2,k,D,3)
# => 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,:+)
例子:
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
关于ruby - 计算 Ruby 数组中的 Fixnums,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22170017/