Issue #8635 has been reported by judofyr (Magnus Holm).

----------------------------------------
Feature #8635: attr_accessor with default block
https://bugs.ruby-lang.org/issues/8635

Author: judofyr (Magnus Holm)
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


=begin

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:

 class Person
   # (1) Simple approach
   attr_writer :name
   def name
     @name ||= 'Hello'
   end
 
   # (2) nil-safe approach
   attr_writer :name
   def name
     return @name if defined? @name
     @name = 'Hello'
   end
 
   # (3) This proposal
   attr_accessor :name do
     'Hello'
   end
 end
 
 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

=end


-- 
http://bugs.ruby-lang.org/