0
0
Rubyprogramming~10 mins

Module_eval for dynamic behavior 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 dynamically using module_eval.

Ruby
module Greeter
  module_eval do
    def [1]
      "Hello!"
    end
  end
end

class Person
  include Greeter
end

puts Person.new.hello
Drag options to blanks, or click blank then click option'
Agreet
Bwelcome
Csay_hello
Dhello
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from 'hello' causes a NoMethodError.
2fill in blank
medium

Complete the code to dynamically add a method that returns the given name.

Ruby
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").name
Drag options to blanks, or click blank then click option'
A"Bob"
Bname
C@name
D"Alice"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a string literal instead of the instance variable.
3fill in blank
hard

Fix the error in the code by completing the module_eval string to define a method.

Ruby
module Calculator
  module_eval "def [1](x, y); x + y; end"
end

class MathOps
  include Calculator
end

puts MathOps.new.add(5, 3)
Drag options to blanks, or click blank then click option'
Aadd
Bcalculate
Cplus
Dsum
Attempts:
3 left
💡 Hint
Common Mistakes
Defining a method with a different name than the one called causes NoMethodError.
4fill in blank
hard

Fill both blanks to dynamically define a method that multiplies a number by a factor.

Ruby
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)
Drag options to blanks, or click blank then click option'
A3
B*
C+
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' or '-' instead of '*' for multiplication.
5fill in blank
hard

Fill all three blanks to dynamically define a method that checks if a number is greater than a threshold.

Ruby
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)
Drag options to blanks, or click blank then click option'
A10
B>
C<
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '==' instead of '>' for the comparison.