Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic attribute in the Struct instance

Tags:

ruby

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
like image 740
ole Avatar asked Dec 30 '14 05:12

ole


2 Answers

You could use an OpenStruct:

require 'ostruct'

p = OpenStruct.new(name: "Bilbo")
p[:surname] = "Jenkins"

p.surname # => "Jenkins"
like image 133
August Avatar answered Sep 23 '22 18:09

August


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.

like image 21
joelparkerhenderson Avatar answered Sep 23 '22 18:09

joelparkerhenderson