Is it possible to create attribute dynamicaly in the Struct
instance?
class Person < Struct.new(:name)
end
p = Person.new("Bilbo")
p[:surname] = "Jenkins" # does not work
You could use an OpenStruct
:
require 'ostruct'
p = OpenStruct.new(name: "Bilbo")
p[:surname] = "Jenkins"
p.surname # => "Jenkins"
You can define new methods on your Person
class by doing this:
Person.send(:define_method, :surname){@surname}
Person.send(:define_method, :surname=){|x|@surname=x}
I prefer define_method
instead of instance_eval
because I try to omit eval
when possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With