Skip to content

Latest commit

 

History

History
114 lines (76 loc) · 1.92 KB

conditionals.md

File metadata and controls

114 lines (76 loc) · 1.92 KB

Conditionals

{id: conditionals}

Comparison Operators

{id: comparison-operators} {i: ==} {i: <} {i: <=} {i: >} {i: >=}

  • ==, <, > <=, >=

Spaceship operator

{id: spaceship-operator} {i: <=>}

  • Spaceship operator <=> returns -1, 0, or 1

if statement

{id: if} {i: if} {i: else} {i: end}

elsif

{id: elsif} {i: elsif}

unless statement

{id: unless} {i: unless}

  • ameba: [C] Style/UnlessElse: Favour if over unless with else

Suffix if

{id: suffix-if} {i: if}

Suffix unless

{id: suffix-unless} {i: unless}

Logical operators

{id: logical-operators}

&&
||
!

Truth-table

{id: truth-table}

case / when

{id: case} {i: case} {i: switch} {i: when}

  • You cannot have the same value in when twice (Crystal protects you from such mistake)

case of types

{id: case-of-types}

Ternary operator and or to set default value

{id: default-value} {i:||} {i: ?:}

Exercise: Number Guessing game - level 0

{id: exercise-number-guessing-game-0}

Level 0

  • Create a file called number_guessing_game_0.cr
  • Using the random module the computer "thinks" about a whole number between 1 and 20.
  • The user has to guess the number. After the user types in the guess the computer tells if this was bigger or smaller than the number it generated, or if it was the same.
  • The game ends after just one guess.

Level 1-

  • Other levels in the next chapter.

Solution: Number Guessing game - level 0

{id: solution-number-guessing-game-0}