方法无法识别布尔值

时间:2017-08-10 08:55:22

标签: ruby

我有一个带两个参数的方法。值(fixnum)和布尔值。

但是,第4行不返回“C”并返回“D”。它没有识别布尔值,我不确定为什么?

def grade(num_books, reads_books)
  if num_books < 10 
    return "D"
  elsif num_books < 10 && reads_books == true
    return "C"
  elsif num_books.between?(10, 20)
    return "C"
  elsif num_books.between?(10,20) && reads_books == true
    return "B"
  elsif num_books > 20
    return "B"
  else
    return "A"
  end
end

grade(9, true)

2 个答案:

答案 0 :(得分:2)

条款的顺序很重要。第一个条件遇到胜利。您可以重新排序子句以使其足够健壮:

def grade(num_books, reads_books)
  if num_books < 10 && reads_books == true
    return "C"
  elsif num_books.between?(10,20) && reads_books == true
    return "B"
  elsif num_books < 10 
    return "D"
  elsif num_books.between?(10, 20)
    return "C"
  elsif num_books > 20
    return "B"
  else
    return "A"
  end
end

grade(9, true)

或者,更多的红宝石:

def grade(num_books, reads_books)
  if reads_books
    case num_books
    when 0...10 then "C"
    when 10..20 then "B"
    else "A"
    end
  else
    case num_books
    when 0...10 then "D"
    when 10..20 then "C"
    else "B"
    end
  end
end

答案 1 :(得分:1)

它返回"D"因为它传递了条件if num_books < 10