Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding attributes to a Ruby object dynamically

Tags:

ruby

I have an object created, and I want, based on some conditional check, to add some attributes to this object. How can I do this? To explain what I want:

A=Object.new if(something happens) {   #make A have another attibute say age   #& store something in A.age  } 
like image 580
Nikhil Garg Avatar asked Jul 08 '10 09:07

Nikhil Garg


2 Answers

First of all the thing about ruby is that it allows a different syntax which is used widely by ruby coders. Capitalized identifiers are Classes or Constants (thanks to sepp2k for his comment), but you try to make it an object. And almost nobody uses {} to mark a multiline block.

a = Object.new if (something happens)   # do something end 

I'm not sure what your question is, but I have an idea, and this would be the solution:

If you know what attributes that class can have, and it's limited you should use

class YourClass   attr_accessor :age end 

attr_accessor :age is short for:

def age   @age end def age=(new_age)   @age = new_age end 

Now you can do something like this:

a = YourClass.new if (some condition)   a.age = new_value end 

If you want to do it completely dynamically you can do something like this:

a = Object.new if (some condition)   a.class.module_eval { attr_accessor :age}   a.age = new_age_value end 
like image 75
jigfox Avatar answered Oct 25 '22 11:10

jigfox


You could use an OpenStruct:

a = OpenStruct.new if condition     a.age = 4 end 

Or just use a plain old hash.

like image 39
David Grayson Avatar answered Oct 25 '22 13:10

David Grayson