0
0
Rubyprogramming~10 mins

Gsub and sub for replacement 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 replace all occurrences of 'cat' with 'dog' in the string.

Ruby
text = "cat and cat"
new_text = text.[1]("cat", "dog")
puts new_text
Drag options to blanks, or click blank then click option'
Asub
Bswap
Creplace
Dgsub
Attempts:
3 left
💡 Hint
Common Mistakes
Using sub instead of gsub causes only the first 'cat' to be replaced.
2fill in blank
medium

Complete the code to replace only the first occurrence of 'apple' with 'orange'.

Ruby
fruits = "apple, apple, apple"
new_fruits = fruits.[1]("apple", "orange")
puts new_fruits
Drag options to blanks, or click blank then click option'
Asub
Bgsub
Creplace
Dswap
Attempts:
3 left
💡 Hint
Common Mistakes
Using gsub replaces all occurrences instead of just the first.
3fill in blank
hard

Fix the error in the code to replace all digits with '#' characters.

Ruby
text = "Phone: 123-456-7890"
new_text = text.[1](/\d/, "#")
puts new_text
Drag options to blanks, or click blank then click option'
Asub
Bgsub
Creplace
Dswap
Attempts:
3 left
💡 Hint
Common Mistakes
Using sub replaces only the first digit, not all.
4fill in blank
hard

Fill both blanks to create a hash mapping words to their lengths, but only for words longer than 4 letters.

Ruby
words = ["apple", "cat", "banana", "dog"]
lengths = {word: word.[1] for word in words if word.[2] 4}
puts lengths
Drag options to blanks, or click blank then click option'
Alength
Bsize
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > causes wrong filtering.
Using size instead of length is valid but not the expected answer here.
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 with length greater than 3.

Ruby
words = ["tree", "sun", "flower", "sky"]
result = {word.[1]: word.[2] for word in words if word.[3] 3}
puts result
Drag options to blanks, or click blank then click option'
Aupcase
Blength
C>
Ddowncase
Attempts:
3 left
💡 Hint
Common Mistakes
Using downcase instead of upcase changes keys incorrectly.
Using < instead of > filters wrong words.