2

Consider the following code:

class Student
  attr_accessor :age, :gender, :school

  def explicit_school_setter
    @school = "Some School"
  end
end

bob = Student.new

bob.age = 16
bob.gender = :male

bob.instance_eval { school = :bvb } # ? Why is this not invoking the setter?

bob.age # => 16
bob.gender # => :male
bob.school # => nil

bob.instance_eval { explicit_school_setter }

bob.school # => "Some School"

bob.school = "Another School"

bob.school # => "Another School"

Why is the setter not working in the instance_eval block?

Jikku Jose
  • 18,306
  • 11
  • 41
  • 61

2 Answers2

3

You are creating a local variable when you call school = :bvb. Change this to self.school = :bvb and you are done.

Daniel Perez
  • 6,335
  • 4
  • 24
  • 28
1

D @school instead of only school inside the block as below

bob.instance_eval { @school = :bvb }