或者语法(||;&&)有两个参数

时间:2016-03-25 03:22:15

标签: ruby

我正在编写此代码以检查数字是否均匀且可被7整除。目标是使用“&&”或“||”。由于我想要偶数和7整除,它将是“&&”。这是我的代码。

input = gets.to_i
def divisible_by_seven?(input)

    div_by_seven = input % 7
    is_even = is_even?(input)

    if div_by_seven == 0 && is_even == true 
        return "is divisible by 7 and is even"

    elsif div_by_seven == 0 && is_even == false
        return "is divisible by 7 but is not even"

    elsif div_by_seven != 0 && is_even == true
        return "is not divisible by 7 but is even"

    else
        return "is not divisible by 7 and is not even"
    end    
end

puts "#{input} #{is_even_and_divisible_by_seven?(input)}"

有没有办法更好地写这个?

3 个答案:

答案 0 :(得分:0)

当然有。

def is_even_and_divisible_by_seven?(input)
  case [(input % 7).zero?, input.even?]
  when [true, true] then "is divisible by 7 and is even"
  when [true, false] then "is divisible by 7 but is not even"
  when [false, true] then "is not divisible by 7 but is even"
  when [false, false] then "is not divisible by 7 and is not even"
end

input = gets.to_i
puts "#{input} #{is_even_and_divisible_by_seven?(input)}"

def is_even_and_divisible_by_seven?(input)
  [(input % 7).zero?, input.even?]
end

input = gets.to_i
x, y = is_even_and_divisible_by_seven?(input)
puts "#{input} is#{" not" unless x} divisible by 7 "\
     "#{x == y ? "and" : "but"} is#{" not" unless y} even"

答案 1 :(得分:0)

快速改进是将div_by_seven = input % 7替换为div_by_seven = input % 7 == 0。另外,将is_even == true替换为is_even,或仅input.even?,将is_even == false替换为!input.even?

def divisible_by_seven_and_even?(input)
  div_by_seven = input % 7 == 0

  if div_by_seven && input.even?
    "is divisible by 7 and is even"
  elsif div_by_seven && !input.even?
    "is divisible by 7 but is not even"
  elsif !div_by_seven && input.even?
    "is not divisible by 7 but is even"
  else
    "is not divisible by 7 and is not even"
  end    
end

答案 2 :(得分:0)

如果一个整数是偶数(除以2)并除以7,那么它除以14。