So I have a class
class MyPerson
attr_accessor :id, :first_name, :surname
def initialize(&block)
instance_eval &block if block_given?
end
end
And I want to create this from another class which looks like this
class MyCallingClass
def initialize
@my_name_generator_object.my_surname = 'Smith'
@my_first_name = 'Bob'
end
def make_my_person
surname_temp = @my_name_generator_object.my_surname
first_name_temp = @my_first_name
my_person = MyPerson.new do
self.surname = surname_temp
self.first_name = first_name_temp
end
end
end
What's happening is that
if I try to pass @my_name_generator to MyPerson in the constructor, it is not nil at the point of instantiating MyPerson, but a value of nil is passed to the initialize method of MyPerson
if I try to pass @my_first_name into the constructor (as above) even though @my_first_name has a value, it is not passed into the initialize method of MyPerson.
if I set @my_name_generator_object.surname and @my_first_name to a temp variable (as in the code above) then it works as expected.
Why is this and is there anything I can do to pass the instance variables directly into the constructor? It just looks messy having to have temp variables to make the code work.