0
0
Rubyprogramming~10 mins

String slicing and indexing 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 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'
A0
B1
C-1
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 0 for the first character index.
Using -1 which gives the last character.
2fill in blank
medium

Complete 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'
A1..3
B2..4
C0..2
D3..5
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong range that misses or adds extra characters.
Using exclusive ranges instead of inclusive.
3fill in blank
hard

Fix 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'
A4..5
B3..4
C-1, 2
D-2, 2
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.
4fill in blank
hard

Fill 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'
A3
B4
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong start index.
Using wrong length that cuts substring incorrectly.
5fill in blank
hard

Fill 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'
Aword
Blength
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using wrong property to get length.