Complete the code to define a method dynamically using module_eval.
module Greeter
module_eval do
def [1]
"Hello!"
end
end
end
class Person
include Greeter
end
puts Person.new.helloThe method defined dynamically is hello, so calling Person.new.hello works.
Complete the code to dynamically add a method that returns the given name.
module PersonModule
module_eval do
def name
[1]
end
end
end
class Person
include PersonModule
def initialize(name)
@name = name
end
end
puts Person.new("Alice").nameThe method returns the instance variable @name which holds the person's name.
Fix the error in the code by completing the module_eval string to define a method.
module Calculator module_eval "def [1](x, y); x + y; end" end class MathOps include Calculator end puts MathOps.new.add(5, 3)
The method called is add, so the dynamically defined method must be named add.
Fill both blanks to dynamically define a method that multiplies a number by a factor.
module Multiplier
module_eval do
def multiply_by_[1](num)
num [2] [1]
end
end
end
class Number
include Multiplier
end
puts Number.new.multiply_by_3(4)The method name includes the factor '3', and the operation is multiplication '*'.
Fill all three blanks to dynamically define a method that checks if a number is greater than a threshold.
module Checker
module_eval do
def greater_than_[1](num)
num [2] [3]
end
end
end
class NumberCheck
include Checker
end
puts NumberCheck.new.greater_than_10(15)The method name includes '10', the comparison operator is '>', and the threshold is 10.