Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the first character of the string.
Ruby
word = "hello" first_char = word[[1]] puts first_char
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 0 for the first character index.
Using -1 which gives the last character.
✗ Incorrect
In Ruby, string indexing starts at 0, so word[0] gives the first character.
2fill in blank
mediumComplete the code to get the substring "ell" from the string.
Ruby
word = "hello" substring = word[[1]] puts substring
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong range that misses or adds extra characters.
Using exclusive ranges instead of inclusive.
✗ Incorrect
The substring "ell" starts at index 1 and ends at index 3 inclusive.
3fill in blank
hardFix the error in the code to get the last two characters of the string.
Ruby
word = "world" last_two = word[[1]] puts last_two
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a range that goes out of bounds.
Using -1 as start index with length 2 which is invalid.
✗ Incorrect
Using negative index -2 with length 2 extracts the last two characters.
4fill in blank
hardFill both blanks to get the substring "cat" from the string.
Ruby
word = "concatenate" substring = word[[1], [2]] puts substring
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong start index.
Using wrong length that cuts substring incorrectly.
✗ Incorrect
The substring "cat" starts at index 3 and has length 3.
5fill in blank
hardFill all three blanks to create a hash with word lengths for words longer than 3 characters.
Ruby
words = ["dog", "elephant", "cat", "bird"] lengths = words.each_with_object({}) { |[3], hash| hash[[1]] = [3].[2] if [3].[2] > 3 } puts lengths
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using wrong property to get length.
✗ Incorrect
We use 'word' as key, 'word.length' as value, and iterate with 'word' over words.