首页 > 解决方案 > 当输入是字符串或浮点数时,如何返回“无效”而不是数组的总和

问题描述

我想返回一个从 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"`,它返回了一个错误。

标签: rubymethodsconditional-statements

解决方案


您还没有在您的方法中放置任何代码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"

推荐阅读