0

I have a method which take two arguments. A value (fixnum) and a boolean.

However, line 4 isn't returning "C" and is returning "D". It isn't recognizing the boolean value and I am unsure why?

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)
1
  • What are the rules for calculating the grade? In particular, the "A" grade cannot be reached, because num_books is either below 10, or between 10 and 20, or above 20. There isn't another "else" that could be met. Commented Aug 10, 2017 at 9:23

2 Answers 2

2

The order of clauses matters. The first one condition met wins. You might reorder clauses to make it robust enough:

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)

or, a bit more rubyish:

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
Sign up to request clarification or add additional context in comments.

5 Comments

I think elsif num_books < 10 should go as a second condition clause. UPD: now I doubt it matters. UPD2: I again think it should go above the elsif num_books.between?(10,20) && reads_books == true as it looks more logical to me :D
The correct answer to your doubts is: elsif should be avoided in ruby :)
Yes, in general of course it should be avoided :) Which for sure makes my above reflections pointless.
The methods are not equivalent. The first one always returns "B" if num_books is above 20, whereas the second one returns "B" or "A" depending on reads_books in that case.
In fact, the original method's else cannot be reached – "A" is never returned. So this is most likely another bug you have fixed ;-)
1

It is returning "D" because it passes the condition if num_books < 10.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.