Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around Hello, causing a NameError.
Using puts inside the method instead of returning a string.
✗ Incorrect
The method should return the string "Hello". Using quotes makes it a string literal.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting instead of adding.
Swapping the order causing confusion.
✗ Incorrect
Adding 10 to the argument num returns the sum. Both 'num + 10' and '10 + num' work.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or subtraction instead of multiplication.
Using division which changes the result.
✗ Incorrect
To multiply the input number by the factor, use the '*' operator.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of exponentiation.
Using addition or subtraction operators.
✗ Incorrect
The '**' operator in Ruby raises a number to the power of another number.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variables without interpolation, resulting in literal text.
Using instance variables without quotes inside the string.
✗ Incorrect
To insert instance variables into a string, use string interpolation with "#{variable}" syntax.