0
0
Rubyprogramming~10 mins

Define_method for dynamic methods 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 define_method.

Ruby
class Greeter
  define_method(:[1]) do |name|
    "Hello, #{name}!"
  end
end
Drag options to blanks, or click blank then click option'
Agreet
Bsay_hello
Chello
Dwelcome
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of a symbol for the method name.
Choosing a method name that does not match the greeting context.
2fill in blank
medium

Complete the code to define a method dynamically that returns the square of a number.

Ruby
class Calculator
  define_method(:[1]) do |x|
    x * x
  end
end
Drag options to blanks, or click blank then click option'
Asquare
Bcube
Cdouble
Dmultiply
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing a method name that does not match the operation.
Using a method name that implies a different calculation.
3fill in blank
hard

Fix the error in the code to define a method dynamically that returns a greeting with a given name.

Ruby
class Person
  define_method([1]) do |name|
    "Hi, #{name}!"
  end
end
Drag options to blanks, or click blank then click option'
A"greet"
B:greet
Cgreet
D'greet'
Attempts:
3 left
💡 Hint
Common Mistakes
Using quotes around the method name instead of a symbol.
Using a bare word without colon which is undefined.
4fill in blank
hard

Fill both blanks to define dynamic methods for addition and subtraction.

Ruby
class MathOps
  define_method(:[1]) do |a, b|
    a + b
  end

  define_method(:[2]) do |a, b|
    a - b
  end
end
Drag options to blanks, or click blank then click option'
Aadd
Bsubtract
Cmultiply
Ddivide
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing method names with operations they don't perform.
Using method names for multiplication or division instead.
5fill in blank
hard

Fill all three blanks to define dynamic methods for multiplication, division, and modulus.

Ruby
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
Drag options to blanks, or click blank then click option'
Amultiply
Bdivide
Cmodulus
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names that don't match the operation.
Confusing modulus with division or multiplication.