2

I want to iterate through a number of arrays and want to dynamically name them from an array of names. Something like this, replace name with the elements from the names array...

names=[a, b, c]
names.each{|name|
name_array1=[]
name_array2=[]
name_array[0][0].each{|i|                           
    if i>0
        name_array1.push([i])
    end
    if i<0
        name_array2.push([i])
    end
  }
}

basically creating the arrays a_array1, a_array2, a_array[0][0], b_array1, b_array2, b_array[0][0], c_array1, c_array2, c_array[0][0]

Is this even possible?

4
  • @pst, no not familiar with hashes... just starting to get a hang of arrays. Commented Jan 30, 2013 at 1:23
  • 2
    @pst Note that you can’t have dynamic local variable names in Ruby 1.9 (though you can in earlier versions), only instance and class variables. Commented Jan 30, 2013 at 1:32
  • @pst, so if I understand correctly this is not doable and I must use hashes if I want to do something similiar? Commented Jan 30, 2013 at 1:39
  • @pst, so instead of renaming the arrays with different names, I should increment the array names like a_array1, b_array1, c_array1... a_array2, b_array2, c_array2... incrementing the numeric value and not changing the name? Sorry if my post is confusing, but as you can probably tell that's exactly what I am right now is confused :) Commented Jan 30, 2013 at 1:53

1 Answer 1

6

Ruby does not support dynamic local variable names1.

However, this can be easily represented using a Hash. A Hash maps a Key to a Value and, in this case, the Key represents a "name" and the Value is the Array:

# use Symbols for names, although Strings would work too
names = [:a, :b, :c]

# create a new hash
my_arrays = {}

# add some arrays to our hash
names.each_with_index { |name, index|
   array = [index] * (index + 1)
   my_arrays[name] = array
}

# see what we have
puts my_arrays

# access "by name"
puts my_arrays[:b]

(There are ways to write the above without side-effects, but this should be a start.)


1 Dynamic instance/class variable names are a different story, but are best left as an "advanced topic" for now and are not applicable to the current task. In the past (Ruby 1.8.x), eval could be used to alter local variable bindings, but this was never a "good" approach and does not work in newer versions.

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

1 Comment

Thank you! Learn something new everyday :)

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.