ruby - 当输入是字符串或浮点数时,如何返回“无效”而不是数组的总和
问题描述
我想返回一个从 0 到 n 的 3 和 5 的倍数和的数组。我想"invalid"
在输入是字符串、浮点数或 < 0 时返回
def is_multiple_of_3_or_5(n)
if n.class == Integer && n > 0
n % 3 == 0 || n % 5 == 0 ? true : false
else
puts "invalid"
end
end
def sum_of_3_and_5_multiples(n)
if n.class == Integer
i = 0
array_of_multiples_of_3_and_5 = Array.new
while i < n
array_of_multiples_of_3_and_5 << i if is_multiple_of_3_or_5(i) == true
i += 1
end
array_of_multiples_of_3_and_5.inject(0, :+)
end
end
sum_of_3_and_5_multiples(-1)
为了得到 3 和 5 的倍数的总和,我得到了这个,但是当我尝试使用 -1 时,它返回了我0
而不是"invalid", with
"string"`,它返回了一个错误。
解决方案
您还没有在您的方法中放置任何代码sum_of_3_and_5_multiples
来处理无效时会发生is_multiple_of_3_or_5
的情况(或者换一种说法,一个字符串)。您也不需要puts 'invalid'
,因为这将返回 null 值。只是'无效'会做:
def is_multiple_of_3_or_5(n)
if n.class == Integer && n > 0
n % 3 == 0 || n % 5 == 0 ? true : false
else
"invalid"
end
end
def sum_of_3_and_5_multiples(n)
if n.class == Integer
i = 0
array_of_multiples_of_3_and_5 = Array.new
while i < n
return "invalid" if is_multiple_of_3_or_5(i).is_a?(String)
array_of_multiples_of_3_and_5 << i if is_multiple_of_3_or_5(i) == true
i += 1
end
array_of_multiples_of_3_and_5.inject(0, :+)
end
end
sum_of_3_and_5_multiples(-1)
=> "invalid"
推荐阅读
- python - paraview-python:无法导入 vtkCommonComputationalGeometry
- r - 根据 R 中另一列中的值添加匹配 ID 的计数器
- excel - Excel。获取#NAME?常规功能错误
- jasmine - 如何等待使用 axios-mock-adapter 完成请求,就像使用 moxios 一样?
- c++ - 为什么只有函数模板的模板参数推导/替换失败?
- java - RecyclerView 没有在项目单击时用片段替换详细信息窗格
- c# - 如何观察取消令牌?
- java - Jenkins android build with gradlew failed:“无法在类路径或引导类路径中找到包 java.lang”
- c# - 如果使用命名约定,则 Automapper 省略 CreateMap
- java - 使用带有换行符号的Java写入xml文件?