Gem Version Build Status Coverage Status

So ruby has Struct but I never use it because: 1. I have to extend the class with Struct 2. It makes your instance_variables public 3. It does not use hash initialization


Add this line to your application’s Gemfile:

“by gem ‘attr_init’

And then execute:

$ bundle

Or install it yourself as:

$ gem install attr_init



“by class Foo attr_init :a, :b end

f = 0, b: 1)

f.a NoMethodError: undefined method: a’ for #Bar:0xb811601c @a=0, @b=1

“f you want to you can override it:


class Foo attr_init :a, :b def initialize(params, opt=nil) if opt.nil? do_other_initializer else attr_init(params) end end end

Initializer with readers

“by class Bar reader_struct :a, :b end

b = 0, b: 1)


b.a = 2 NoMethodError: undefined method: a=‘ for #Bar:0xb931e250 @a=0, @b=1

Initializer with accessors

“by class Dah accessor_struct :a, :b end

d = 0, b: 1)


d.a = 2

Struct adds #to_h

“by class Dah accessor_struct :a, :b end

d = 0, b: 1)



  1. Fork it ([johnmcconnell]/attr_init/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request