Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to call the method dynamically using send.
Ruby
class Greeter def hello "Hello!" end end g = Greeter.new puts g.[1](:hello)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'call' instead of 'send' causes a NoMethodError.
Using 'invoke' or 'execute' are not valid Ruby methods for this purpose.
✗ Incorrect
The send method in Ruby allows you to call a method by name dynamically.
2fill in blank
mediumComplete the code to call the method with an argument dynamically using send.
Ruby
class Calculator def square(n) n * n end end calc = Calculator.new result = calc.[1](:square, 4) puts result
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'call' or 'apply' which are not Ruby methods for dynamic calls.
Forgetting to pass the argument after the method name.
✗ Incorrect
send allows calling a method with arguments dynamically by passing the method name and arguments.
3fill in blank
hardFix the error in calling a private method dynamically using send.
Ruby
class Secret private def whisper "This is a secret" end end s = Secret.new puts s.[1](:whisper)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using public_send causes NoMethodError for private methods.
Using call or invoke are not valid Ruby methods.
✗ Incorrect
send can call private methods dynamically, while public_send cannot.
4fill in blank
hardFill both blanks to call a method dynamically and pass two arguments.
Ruby
class Multiplier def multiply(a, b) a * b end end m = Multiplier.new result = m.[1](:multiply, [2], 5) puts result
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using call instead of send causes errors.
Passing wrong argument values.
✗ Incorrect
send calls the method :multiply with arguments 3 and 5.
5fill in blank
hardFill all three blanks to call a method dynamically, pass an argument, and convert the result to a string.
Ruby
class Repeater def repeat(word, times) word * times end end r = Repeater.new output = r.[1](:repeat, [2], 3).[3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using method name 'repeat' instead of send to call dynamically.
Not converting the result to string with to_s.
✗ Incorrect
send calls :repeat with "Hi" and 3, then to_s converts the result to string.