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)




@adam = => 1, :name => “Adam”)

@eve = => 2)

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

print @people

puts! do |person|

    person ||= => 3, :name => “Some default”)

    if = “Eve”




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”>]


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” which generally returns nil. Probably not what you want

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

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 *