Elsif branching


#1


the correct message for grade A is not showing up. instead no matter what grade it is I always get the first message "not good". why is this happening?


grade = "A"
if grade == "D" || "F"
	"not good"
elsif grade == "B" || "C"
	"not great"
elsif grade == "A"
	"awesome"
else 
	"not graded"
end


#2

" If grade is equal to 'D' or 'F' " is the human-speak of the above expression, and our brains can handle it. Ruby does not think this way.

The OR operands need to be independent expressions.

if grade == "D" || grade == "F"

To clarify we need to do a quick review of logical expressions.

T || T  => true

BUT, only because one of the operands is true, the first one. The expression is short-circuit evaluated to true without testing the second operand.

F || T  => true

again, because one of the operands is true, the last one. There is no short-circuiting but the outcome is the same.

Now consider truthy and the role this plays when working with non-boolean data types. A zero (0), nil and the empty string ("" / '') all evaluate to false; everything else evaluates to true.

Let's say grade is niether 'D' nor 'F'. The above expression will still yield true since 'F' is truthy.


#3

OMG thank you so much, I think I spent like 2 hrs trying to do different things to make it work LOL. Thank you!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.