tags:

views:

34

answers:

2

This probably is a simple doubt but I am very new to Ruby.

I have an object created . 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

}
A: 

You can use instance_variable_set to set a variable on an instance of the Object class (and instance_variable_get to get it.) The Object class doesn't have any attributes you can set directly.

However, I suspect this is not the best solution for what you are trying to achieve; it is not the norm to directly work with the Object class, but rather to define or use classes that inherit from it, that have the attributes you want to work with.

DanSingerman
+5  A: 

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 {} do 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 dynamical you can do something like this:

a = Object.new
if (something happens)
  a.class.module_eval { attr_accesor :age}
  a.age = new_age_value
end
jigfox
using capitals for class is not ruby "syntax" but common convention. I told you already - I am not yet too much a ruby guy.Btw your solution works good enough for me. Thanks.
Nikhil Garg
I know that this is common convention, that's why I wrote "Capitalized identifiers **should** be Classes" and I saw that you're new to ruby, so I thought, I show you how most ruby coders would do it. And the syntax thing was about the paranthesis for the if block
jigfox
@Nikhil: Actually it *is* syntax, not a matter of convention. Any identifier that start with a capital letter is a constant in ruby. So `a = Object.new` and `A = Object.new` do too very different things (the first defines a local variable, the other a global constant).
sepp2k
AAh...That would be useful to me! Wonder how I never came across it. Thanks anyway :)
Nikhil Garg
@sepp2k, Thank you, I didn't thought of this
jigfox