Bird
0
0

Which of the following is the correct syntax to create a new class with Class.new and add a method greet that returns "Hello"?

easy📝 Syntax Q12 of 15
Ruby - Metaprogramming Fundamentals
Which of the following is the correct syntax to create a new class with Class.new and add a method greet that returns "Hello"?
AMyClass = Class.new do def greet return "Hello" end end
BMyClass = Class.new { greet() = "Hello" }
CMyClass = Class.new { def greet; "Hello"; end }
DMyClass = Class.new { def greet() puts "Hello" }
Step-by-Step Solution
Solution:
  1. Step 1: Check correct block syntax for Class.new

    The block can be given with curly braces or do-end. Inside, method definitions use def method_name; ...; end.
  2. Step 2: Validate method definition and return value

    MyClass = Class.new { def greet; "Hello"; end } correctly defines greet returning "Hello". MyClass = Class.new do def greet return "Hello" end end is correct syntax but missing the 'end' for the block in MyClass = Class.new do def greet return "Hello" end end, so MyClass = Class.new do def greet return "Hello" end end is invalid as given. MyClass = Class.new { greet() = "Hello" } uses invalid method syntax. MyClass = Class.new { def greet() puts "Hello" } uses puts which prints but does not return the string.
  3. Final Answer:

    MyClass = Class.new { def greet; "Hello"; end } -> Option C
  4. Quick Check:

    Correct method syntax inside Class.new block = MyClass = Class.new { def greet; "Hello"; end } [OK]
Quick Trick: Use def inside Class.new block with proper syntax [OK]
Common Mistakes:
  • Using puts instead of returning a string
  • Incorrect block syntax for Class.new
  • Invalid method definition syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes