Domanda

I'd like to define attr_accessor on a class dynamically, but it makes the generated methods private. How can I make the following not throw an error without using the normal class syntax or writing the methods myself?

klass = Class.new
klass.send(:attr_accessor, 'name')
instance = klass.new
instance.name

NoMethodError: private method `name' called for #<#<Class:0x007fce725ec660>:0x007fce72607b18>
È stato utile?

Soluzione

As described in the examples from the documentation, Class.new is passed a block, so I would do as below:

klass = Class.new do
  attr_accessor :name
end

instance = klass.new
instance.name = "Foo"
instance.name #=> "Foo"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top