0
0
Rubyprogramming~10 mins

Common patterns and character classes 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 check if the string contains only digits.

Ruby
if str =~ /\A[1]+\z/
  puts "Only digits"
else
  puts "Contains other characters"
end
Drag options to blanks, or click blank then click option'
A\d
B\w
C\s
D\D
Attempts:
3 left
💡 Hint
Common Mistakes
Using \w matches letters and digits, not only digits.
Using \D matches non-digit characters, which is opposite of what is needed.
2fill in blank
medium

Complete the code to find all whitespace characters in the string.

Ruby
matches = str.scan(/[1]/)
puts matches
Drag options to blanks, or click blank then click option'
A\S
B\s
C\w
D\d
Attempts:
3 left
💡 Hint
Common Mistakes
Using \S which matches non-whitespace characters.
Using \w which matches letters and digits, not spaces.
3fill in blank
hard

Fix the error in the regex to match a string that starts with a letter.

Ruby
if str =~ /^[1]/i
  puts "Starts with a letter"
else
  puts "Does not start with a letter"
end
Drag options to blanks, or click blank then click option'
A\s
B[0-9]
C\d
D[a-z]
Attempts:
3 left
💡 Hint
Common Mistakes
Using \d which matches digits, not letters.
Using [0-9] which matches digits, not letters.
4fill in blank
hard

Fill both blanks to create a hash with words as keys and their lengths as values, only for words longer than 3 characters.

Ruby
lengths = words.each_with_object({}) { |word, h| h[word] = word.[1] if word.[2] 3 }
Drag options to blanks, or click blank then click option'
Alength
Bsize
Clength >
Dsize >
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length' as a method without parentheses in this context.
Using 'length >' or 'size >' as one option instead of separating method and operator.
5fill in blank
hard

Fill all three blanks to create a hash with uppercase words as keys and their lengths as values, only for words containing digits.

Ruby
result = words.each_with_object({}) { |word, h| h[word.[1]] = word.[2] if word =~ /[3]/ }
Drag options to blanks, or click blank then click option'
Aupcase
Bsize
C\d
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length' instead of 'size' inconsistently.
Using incorrect regex like /\w/ which matches letters and digits.