0
0
Rubyprogramming~10 mins

Define_method with closures 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 named 'greet' that returns 'Hello'.

Ruby
class Person
  define_method(:greet) do
    [1]
  end
end

p = Person.new
puts p.greet
Drag options to blanks, or click blank then click option'
A"Hello"
BHello
Creturn Hello
Dputs "Hello"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around Hello, causing a NameError.
Using puts inside the method instead of returning a string.
2fill in blank
medium

Complete the code to define a method 'add' that takes one argument and adds it to 10.

Ruby
class Calculator
  define_method(:add) do |num|
    [1]
  end
end

calc = Calculator.new
puts calc.add(5)
Drag options to blanks, or click blank then click option'
A10 + num
Bnum + 10
Cnum - 10
D10 - num
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting instead of adding.
Swapping the order causing confusion.
3fill in blank
hard

Fix the error in the code to correctly define a method 'multiplier' that multiplies input by a fixed factor.

Ruby
class Multiplier
  def initialize(factor)
    @factor = factor
  end

  define_method(:multiply) do |num|
    num [1] @factor
  end
end

m = Multiplier.new(3)
puts m.multiply(4)
Drag options to blanks, or click blank then click option'
A/
B+
C-
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or subtraction instead of multiplication.
Using division which changes the result.
4fill in blank
hard

Fill both blanks to define a method 'power' that raises input to a fixed exponent stored in @exp.

Ruby
class Power
  def initialize(exp)
    @exp = exp
  end

  define_method(:power) do |base|
    base [1] @exp
  end
end

p = Power.new(2)
puts p.power(5)
Drag options to blanks, or click blank then click option'
A**
B*
C+
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of exponentiation.
Using addition or subtraction operators.
5fill in blank
hard

Fill all three blanks to define a method 'describe' that returns a string with the object's name and age.

Ruby
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  define_method(:describe) do
    "[1] is [2] years old."
  end
end

person = Person.new("Alice", 30)
puts person.describe
Drag options to blanks, or click blank then click option'
A@name
B@age
C"#{@name}"
D"#{@age}"
Attempts:
3 left
💡 Hint
Common Mistakes
Using variables without interpolation, resulting in literal text.
Using instance variables without quotes inside the string.