Bird
0
0

Which of the following is the correct syntax to add a method hello to class Person using class_eval?

easy📝 Syntax Q3 of 15
Ruby - Advanced Metaprogramming
Which of the following is the correct syntax to add a method hello to class Person using class_eval?
APerson.class_eval do; def hello; 'Hi'; end; end
BPerson.class_eval { def hello; 'Hi'; end }
CPerson.instance_eval { def hello; 'Hi'; end }
DPerson.instance_eval do; def hello; 'Hi'; end; end
Step-by-Step Solution
Solution:
  1. Step 1: Identify class_eval syntax

    class_eval can be called with a block using curly braces or do-end without semicolons.
  2. Step 2: Check syntax correctness

    Person.class_eval { def hello; 'Hi'; end } uses correct syntax with curly braces and defines method inside the block properly.
  3. Final Answer:

    Person.class_eval { def hello; 'Hi'; end } -> Option B
  4. Quick Check:

    Correct class_eval syntax = Person.class_eval { def hello; 'Hi'; end } [OK]
Quick Trick: Use class_eval with braces or do-end without semicolons [OK]
Common Mistakes:
  • Using instance_eval instead of class_eval for class methods
  • Adding semicolons inside do-end blocks
  • Wrong block delimiters or syntax errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes