0

I have a list of attributes. Each attribute will be setted as an empty array and i want to push elements to each array.

I figured out how to create a dynamic array with instance_variable_set but i couldn't push elements to it.

That's what i did:

attributes = ["eye","hair_color","hair_size","hair_type"]
i = 0
attributes.each do |a|
    # Dynamic arrays are created, like: @eye = []
    instance_variable_set("@#{a}", [])
    # My attempt to push element
    "@#{a}".push(i)
    i += 1
end

How can i push an element to those dynamic arrays?

3 Answers 3

2

instance_variable_get("@#{a}").push(i) will work

Sign up to request clarification or add additional context in comments.

Comments

1

Petr Balaban has it right. I thought I would also note that you can do each_with_index instead of setting and incrementing i manually:

attributes = ["eye","hair_color","hair_size","hair_type"]

attributes.each_with_index do |a,i|
  # Dynamic arrays are created, like: @eye = []
  instance_variable_set("@#{a}", [])
  # As Petr noted...
  instance_variable_get("@#{a}").push(i)
end

Comments

1

Another approach would be:

attributes = %w|eye hair_color hair_size hair_type|
attributes.each_with_index do |a, idx|
  self.class.send :attr_accessor, a.to_sym
  public_send "#{a}=", idx
  (public_send a) << idx
end

Now you have an access to these variables by getter:

hair_size
#⇒ 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.