Ruby: completing object initialization

Say you’ve got some partially initialised objects and want to complete the initialisation. 

Here’s an example: 

class Person 

    attr_accessor :id, :name

    def initialize(init)

        init.each_pair do |key, val|

            instance_variable_set(‘@’ + key.to_s, val)

        end

    end

end

@adam = Person.new(:id => 1, :name => “Adam”)

@eve = Person.new(:id => 2)

@people = [ @adam, @eve, nil ]

print @people

puts

@people.map! do |person|

    person ||= Person.new(:id => 3, :name => “Some default”)

    if person.name.nil?

        person.name = “Eve”

    end

    person

end 

print @people 

This prints out:

[#<Person:0x007faf2bae37d8 @id=1, @name=”Adam”>, #<Person:0x007faf2bae3648 @id=2>, nil]

[#<Person:0x007faf2bae37d8 @id=1, @name=”Adam”>, #<Person:0x007faf2bae3648 @id=2, @name=”Eve”>, #<Person:0x007faf2bae3328 @id=3, @name=”Some default”>]

Notes:

1. the map! will directly change the contents of @people

2. you need to have ‘person’ at the end of the map! method as the value returned will be used to change the value of person. And if you don’t have it there, the next return value would be “if person.name.nil?” which generally returns nil. Probably not what you want

3. Finally, ‘return person’ would not work as you’d just break out early. See: 

http://stackoverflow.com/questions/4601498/what-is-the-point-of-return-in-ruby

4. Finally, this isn’t the most idiomatic Ruby code. Do a search for idiomatic to find a more Ruby’ish version.

Leave a Reply

Your email address will not be published. Required fields are marked *