commit 436cf72778361afaee4453b95288233865551a5b
parent b711a629a30c186e9cb1eb6067a86c67ec6b9bfe
Author: David Voznyarskiy <31452046-davidvoz@users.noreply.gitlab.com>
Date: Thu, 1 Jan 2026 13:47:08 -0800
exercise 28 case added
Diffstat:
2 files changed, 80 insertions(+), 0 deletions(-)
diff --git a/exercises/28_case.sh b/exercises/28_case.sh
@@ -0,0 +1,64 @@
+#!/bin/sh
+
+# Instead of using if, elif, elif, elif, else, there's a more concise
+# (and often faster) method you can use; case.
+#
+# $ echo "Enter a letter: "
+# $ read user_input
+# $
+# $ case "$user_input" in
+# $ [a-z])
+# $ echo "Entered: lowercase"
+# $ ;;
+# $ [A-Z])
+# $ echo "Entered: uppercase"
+# $ ;;
+# $ [0-9])
+# $ echo "I said letter, not number"
+# $ ;;
+# $ *) # for everything else
+# $ echo "What?"
+# $ ;;
+# $ esac
+#
+# The snippet above should be self explanatory. Now, for other cases, it
+# can look like this
+#
+# $ case "$item" in
+# $ apple|banana|orange) # apple or banana or orange
+# $ echo "Food item"
+# $ ;;
+# $ book)
+# $ echo "leisure item"
+# $ ;;
+# $ *)
+# $ echo "unknown"
+# $ ;;
+# $ esac
+#
+# It's better to use 'case' instead of 'if' when you are pattern
+# matching, which means you can avoid using grep. It can be better to
+# do 'if' instead of 'case' when there's arithmetic, like playing a
+# hotter/colder game by having a user try to find a number.
+#
+# Below is the unfinished work of a rock-paper-scissors game between
+# a player and the computer
+
+choices="rock paper scissors"
+computer_choice=$(echo "$choices" | tr ' ' '\n' | shuf -n 1)
+printf "Choose rock paper or scissors: "
+read player_choice
+
+# The code snippet above needs no changing.
+# Have all the echo statements be just those 3 words exactly
+# Error messages can be helpful here
+case "$player_choice" in
+ rock)
+ case "$computer_choice" in
+ rock) echo "tie" ;; # this is a valid way of condensing code
+ paper) echo "lost" ;;
+ scissors) echo "won" ;;
+ *)
+ echo "ERROR invalid option"
+ ;;
+esac
diff --git a/tests/28_case.sh b/tests/28_case.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+
+set -eu
+RED="\033[31m"
+GREEN="\033[32m"
+RESET="\033[0m"
+
+failed() {
+ printf "${RED}Failed${RESET}\n"
+ exit 1
+}
+
+printf "scissors\n" | sh exercises/28_case.sh | grep -Eq "tie|lost|won" || failed
+printf "scissor\n" | sh exercises/28_case.sh | grep -Eq "tie|lost|won" && failed
+
+printf "${GREEN}Passed${RESET}\n"