我有一个包含字符、数字和浮点值的数组。
a[] = {'a',2,2.5}
我必须将每个整数和 float 乘以 2,并且不应对字符进行任何操作。
我的解决方案-
def self.double_numbers(input)
input.map do |input_element|
if input_element.is_a? Integer
input_element.to_i * 2
elsif input_element.is_a? Float
input_element.to_Float * 2
end
end
end
输入无效
a[] = {'a',2,2.5}
它回来了
0 4 4
最佳答案
您可以使用 map
并检查数组中的每个元素是否为 Numeric
,如果是,则将其乘以 2,然后您可以将结果压缩为nil
值:
p ['a', 2, 2.5].map{|e| e * 2 if e.is_a? Numeric}.compact
# => [4, 5.0]
如果要保留不会应用*2
操作的元素,则:
p ['a', 2, 2.5].map{|e| e.is_a?(Numeric) ? e * 2 : e}
您也可以使用 grep
来简化检查,然后映射您的纯数字值:
p ['a', 2, 2.5].grep(Numeric).map{|e| e*2}
# => [4, 5.0]
我不知道这样做的副作用,但看起来不错(当然如果输出不仅仅是数字对象):
class Numeric
def duplicate
self * 2
end
end
p ['a', 2, 2.5].grep(Numeric).map(&:duplicate)
或者还有:
p ['a', 2, 2.5].grep(Numeric).map(&2.method(:*))
# [4, 5.0]
关于ruby - 如何在ruby中将数组中的每个数字乘以2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44939123/