0
0
Rubyprogramming~10 mins

Guard clauses pattern in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return early if the number is negative.

Ruby
def check_number(num)
  return 'Negative number' if [1]
  'Number is positive'
end
Drag options to blanks, or click blank then click option'
Anum < 0
Bnum == 0
Cnum > 0
Dnum >= 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < causes the guard clause to trigger incorrectly.
Checking for equality to zero does not catch negative numbers.
2fill in blank
medium

Complete the guard clause to return early if the string is empty.

Ruby
def greet(name)
  return 'No name provided' if [1]
  "Hello, #{name}!"
end
Drag options to blanks, or click blank then click option'
Aname.nil?
Bname == ' '
Cname.length > 0
Dname.empty?
Attempts:
3 left
💡 Hint
Common Mistakes
Using nil? misses empty strings that are not nil.
Checking for a space character does not detect empty strings.
3fill in blank
hard

Fix the error in the guard clause to correctly return if the array is nil or empty.

Ruby
def process_list(list)
  return 'No items' if [1]
  list.map(&:upcase)
end
Drag options to blanks, or click blank then click option'
Alist.nil? || list.length > 0
Blist.empty? && list.nil?
Clist.nil? || list.empty?
Dlist.nil? && list.empty?
Attempts:
3 left
💡 Hint
Common Mistakes
Using && instead of || causes the condition to fail when only one is true.
Checking length > 0 is the opposite of what is needed.
4fill in blank
hard

Fill both blanks to create a guard clause that returns early if the user is not logged in or inactive.

Ruby
def access_page(user)
  return 'Access denied' if [1] || [2]
  'Welcome!'
end
Drag options to blanks, or click blank then click option'
A!user.logged_in?
Buser.active?
C!user.active?
Duser.logged_in?
Attempts:
3 left
💡 Hint
Common Mistakes
Using positive checks without negation causes the guard clause to trigger incorrectly.
Mixing up active and logged_in methods.
5fill in blank
hard

Fill all three blanks to create a guard clause that returns early if the input is nil, empty, or not a string.

Ruby
def validate_input(input)
  return 'Invalid input' if [1] || [2] || [3]
  'Input is valid'
end
Drag options to blanks, or click blank then click option'
Ainput.nil?
Binput.empty?
C!input.is_a?(String)
Dinput.length == 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using input.length == 0 without checking for nil causes errors.
Not checking the type allows invalid inputs to pass.