Why does this code only evaluate the lowercase characters?

def hand_score(hand)
score = 0

hand.each_char do |char|
if char == (“a” || “A”)
score += 4
if char == (“k” || “K”)
score += 3
if char == (“q” || “Q”)
score += 2
if char == (“j” || “J”)
score += 1

return score

puts hand_score(“AQAJ”) => 0
puts hand_score(“jJka”) #=> 8

This is because of short-circuit evaluation and how OR works.

First of all, all operators return a value and OR always returns the first value that evaluated to true.

true || false will give you true
"k" || "K" will give you "k"
"K" || "k" will give you "K"
false || "x" || true will give you "x"

AND works similarly but returns the last value that evaluated to true.

In short, OR returns the first truthy value while AND returns the last.

1 Like

Thanks for the reply!

Based on that, with the hand of “AQAJ”, the first char of “A” would return false for char == “a”, so shouldn’t it skip over that and then check if char == “A”, evaluate to true, and then do score += 4 ?

TL;DR: You have to write your check as char == "a" || char == "A". Read further to understand why.

When you write it as char == ("a" || "A"), what you’re actually comparing is char to the result of parentheses evaluation. Remember, with parentheses you change the order of operations and force the program to evaluate expression inside first before anything else, just like in math.

Let’s say that char is currently "a" and your conditional check is char == ("A" || "a"). It essentially looks like "a" == ("A" || "a") to Ruby. However because there are parentheses, you are forcing Ruby to first evaluate whatever is inside them first. If you recall from my previous post on how OR works then you understand why the result will be the first truthy value or “A”.

Once parentheses have been evaluated, the expression is basically just "a" == "A", which will obviously be false.

Hopefully now you understand why your check was failing and I hope the above explanation wasn’t confusing.

Edit: Because I can’t edit my first reply let me add something to my first reply on how OR and AND function.

OR returns the first truthy value it finds. If there are no truthy values it will return the last value it checked.

AND returns the last value it checked in both scenarios.

1 Like

Perfect explanation. Thank you so much for your help, I really appreciate it :slight_smile: