0
0
Rubyprogramming~10 mins

Why metaprogramming is powerful in Ruby - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a method dynamically using define_method.

Ruby
class Greeting
  [1] :hello do
    puts 'Hello, world!'
  end
end
Drag options to blanks, or click blank then click option'
Amethod_missing
Bdef
Cattr_accessor
Ddefine_method
Attempts:
3 left
💡 Hint
Common Mistakes
Using def instead of define_method for dynamic method creation.
2fill in blank
medium

Complete the code to catch calls to undefined methods using method_missing.

Ruby
class Dynamic
  def [1](method_name, *args)
    puts "You called #{method_name} with #{args.inspect}"
  end
end
Drag options to blanks, or click blank then click option'
Arespond_to_missing?
Bmethod_missing
Cdefine_method
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing method_missing with respond_to_missing? or send.
3fill in blank
hard

Fix the error in the code to dynamically create getter methods using define_method.

Ruby
class Person
  [:name, :age].each do |attr|
    [1] attr do
      @#{attr}
    end
  end
end
Drag options to blanks, or click blank then click option'
Adef
Battr_accessor
Cdefine_method
Dattr_reader
Attempts:
3 left
💡 Hint
Common Mistakes
Using def inside a block, which is invalid syntax.
4fill in blank
hard

Fill both blanks to create a method that responds to any undefined method by printing its name and arguments.

Ruby
class Catcher
  def [1](method_name, *args)
    puts "Called #{method_name} with #{args[2]"
  end
end
Drag options to blanks, or click blank then click option'
Amethod_missing
Binspect
Cjoin
Dto_s
Attempts:
3 left
💡 Hint
Common Mistakes
Using to_s instead of inspect for argument display.
5fill in blank
hard

Fill all three blanks to create a dynamic attribute writer method using define_method.

Ruby
class DynamicAttr
  [:title, :author, :year].each do |attr|
    [1] "#{attr}=" do |value|
      @[2] = [3]
    end
  end
end
Drag options to blanks, or click blank then click option'
Adefine_method
Battr
Cvalue
Dattr_accessor
Attempts:
3 left
💡 Hint
Common Mistakes
Using attr_accessor instead of define_method for dynamic method creation.