Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to reopen the String class and add a method.
Ruby
class String def [1] "Hello, " + self end end puts "World".greet
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from the one called on the string.
Forgetting to reopen the class before defining the method.
✗ Incorrect
The method 'greet' is added to the String class and called on the string "World".
2fill in blank
mediumComplete the code to reopen the Integer class and add a method that doubles the number.
Ruby
class Integer def [1] self * 2 end end puts 5.double
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not match the call.
Not returning the correct calculation.
✗ Incorrect
The method 'double' is added to Integer and returns the number multiplied by 2.
3fill in blank
hardFix the error in reopening the Array class to add a method that returns the first element doubled.
Ruby
class Array def double_first [1] * 2 end end puts [1, 2, 3].double_first
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self[1]' which accesses the second element.
Using 'first()' without 'self'.
✗ Incorrect
Using 'self.first' correctly accesses the first element of the array.
4fill in blank
hardFill both blanks to reopen the Hash class and add a method that returns keys with values greater than 10.
Ruby
class Hash def keys_with_large_values select { |[1], [2]| [2] > 10 }.keys end end puts({a: 5, b: 15, c: 20}.keys_with_large_values)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'key' and 'value' which are valid but not the correct answer here.
Mixing up the order of key and value.
✗ Incorrect
The block variables 'k' and 'v' represent key and value respectively in the Hash select method.
5fill in blank
hardFill all three blanks to reopen the Numeric class and add a method that returns the number squared if positive, else zero.
Ruby
class Numeric def positive_square if [1] > 0 [2] [3] 2 else 0 end end end puts 4.positive_square puts (-3).positive_square
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' instead of '**' for squaring.
Not using 'self' to refer to the number.
✗ Incorrect
Check if 'self' is positive, then return 'self ** 2' (square). The '*' operator is incorrect for exponentiation.