0
0
Rubyprogramming~10 mins

Class_eval and instance_eval 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 add a method to the class using class_eval.

Ruby
class MyClass
  class_eval do
    def greet
      puts [1]
    end
  end
end

obj = MyClass.new
obj.greet
Drag options to blanks, or click blank then click option'
AHello from class_eval!
B"Hello from instance_eval!"
C"Hello from class_eval!"
Dputs "Hello"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string.
Using instance_eval instead of class_eval here.
2fill in blank
medium

Complete the code to define an instance variable using instance_eval.

Ruby
class MyClass
  def initialize
    @name = "Ruby"
  end
end

obj = MyClass.new
obj.instance_eval do
  @name = [1]
end

puts obj.instance_eval { @name }
Drag options to blanks, or click blank then click option'
AChanged by instance_eval
Bname
C:Changed
D"Changed by instance_eval"
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning a string without quotes.
Trying to access @name without instance_eval.
3fill in blank
hard

Fix the error in the code by completing the blank to call instance_eval correctly.

Ruby
class MyClass
  def initialize
    @value = 10
  end
end

obj = MyClass.new
result = obj.[1] { @value * 2 }
puts result
Drag options to blanks, or click blank then click option'
Ainstance_eval
Bself_eval
Ceval
Dclass_eval
Attempts:
3 left
💡 Hint
Common Mistakes
Using class_eval instead of instance_eval.
Using eval which is a Kernel method, not related to the object.
4fill in blank
hard

Fill both blanks to add a class method using class_eval and call it.

Ruby
class MyClass
  [1].class_eval do
    def self.say_hello
      "Hello from class method"
    end
  end
end

puts MyClass.[2]
Drag options to blanks, or click blank then click option'
Aself
Binstance
Csay_hello
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Calling class_eval on an instance.
Calling a method that does not exist.
5fill in blank
hard

Fill all three blanks to define an instance variable with instance_eval, define a method with class_eval, and call both.

Ruby
class MyClass
  [1].class_eval do
    def greet
      "Hello, #{@name}!"
    end
  end
end

obj = MyClass.new
obj.[2] do
  @name = [3]
end

puts obj.greet
Drag options to blanks, or click blank then click option'
Aself
Binstance_eval
C"Ruby Learner"
Dclass_eval
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up class_eval and instance_eval calls.
Not quoting the string for @name.