0
0
Rubyprogramming~10 mins

Respond_to_missing? convention 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 define a method that checks if an object responds to a method name.

Ruby
def respond_to_missing?(method_name, include_private = false)
  method_name == :[1]
end
Drag options to blanks, or click blank then click option'
Abaz
Bbar
Cqux
Dfoo
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of a symbol for method_name comparison.
Checking for the wrong method name symbol.
2fill in blank
medium

Complete the code to properly override respond_to_missing? to handle a dynamic method.

Ruby
def respond_to_missing?(method_name, include_private = false)
  method_name.to_s.start_with?('find_') || [1]
end
Drag options to blanks, or click blank then click option'
Afalse
Bsuper
Ctrue
Dnil
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true or false directly without calling super.
Using nil which is not a boolean.
3fill in blank
hard

Fix the error in the method_missing implementation to correctly handle missing methods.

Ruby
def method_missing(method_name, *args, &block)
  if method_name.to_s.start_with?('find_')
    "Finding record for #{method_name}"
  else
    [1]
  end
end
Drag options to blanks, or click blank then click option'
Aputs 'Error'
Breturn nil
Csuper
Draise ArgumentError
Attempts:
3 left
💡 Hint
Common Mistakes
Returning nil silently hides errors.
Raising the wrong exception type.
Printing errors instead of raising.
4fill in blank
hard

Fill both blanks to complete a class that uses respond_to_missing? and method_missing to handle dynamic methods starting with 'get_'.

Ruby
class DynamicGetter
  def respond_to_missing?(method_name, include_private = false)
    method_name.to_s.start_with?([1]) || super
  end

  def method_missing(method_name, *args, &block)
    if method_name.to_s.start_with?([2])
      "Got #{method_name}"
    else
      super
    end
  end
end
Drag options to blanks, or click blank then click option'
A'get_'
B'set_'
C'find_'
D'fetch_'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different prefixes in the two methods.
Forgetting to call super in either method.
5fill in blank
hard

Fill all three blanks to complete a class that dynamically responds to methods starting with 'calculate_', returning the calculation name.

Ruby
class Calculator
  def respond_to_missing?(method_name, include_private = false)
    method_name.to_s.start_with?([1]) || super
  end

  def method_missing(method_name, *args, &block)
    if method_name.to_s.start_with?([2])
      "Calculating #{method_name.to_s[[3]..]}"
    else
      super
    end
  end
end
Drag options to blanks, or click blank then click option'
A'calculate_'
B'compute_'
C10
D8
Attempts:
3 left
💡 Hint
Common Mistakes
Using different prefixes in the two methods.
Incorrect slice index causing wrong substring.
Not calling super in fallback cases.