Complete the code to define a method dynamically using define_method.
class Greeter define_method(:[1]) do |name| "Hello, #{name}!" end end
The method name to define dynamically is greet. Using define_method(:greet) creates a method called greet that takes a name and returns a greeting.
Complete the code to define a method dynamically that returns the square of a number.
class Calculator define_method(:[1]) do |x| x * x end end
The method name square matches the operation of returning the square of a number.
Fix the error in the code to define a method dynamically that returns a greeting with a given name.
class Person define_method([1]) do |name| "Hi, #{name}!" end end
The method name must be a symbol, so :greet is correct. Using strings or bare words causes errors.
Fill both blanks to define dynamic methods for addition and subtraction.
class MathOps define_method(:[1]) do |a, b| a + b end define_method(:[2]) do |a, b| a - b end end
The first method is named add for addition, and the second is subtract for subtraction.
Fill all three blanks to define dynamic methods for multiplication, division, and modulus.
class AdvancedMath define_method(:[1]) do |a, b| a * b end define_method(:[2]) do |a, b| a / b end define_method(:[3]) do |a, b| a % b end end
The methods are named multiply, divide, and modulus matching their operations.