attr_accessor with default block
It's quite common to define attributes (like attr_reader, attr_accessor) with default values. It would be useful if Ruby provided a helper method for this case. attr_accessor and attr_reader can support this nicely using a default block:
(1) Simple approach¶
@name ||= 'Hello'
(2) nil-safe approach¶
return @name if defined? @name
@name = 'Hello'
(3) This proposal¶
attr_accessor :name do
p = Person.new
p.instance_variable_get(:@name) # => nil
p.name # => 'Hello'
p.instance_variable_get(:@name) # => 'Hello'
Problems with current approaches:
- The reader and the writer looks widely different
- Solution 1 doesn't work as intended when the default value may evaulate to nil/false
- Solution 2 requires you to write the attribute name five times