JoMojo
JoMojo

Reputation: 404

Ruby - split and rename subarrays

As the title says... if I have an array containing subarrays is it possible to split the array and rename the new split arrays? I know I could simply type new_array=array[0] and so on but the problem is that the original array containing the sub arrays will vary in size.

original array...

array=[["a", "1", "2", "3"], ["b", "1", "2", "3"],  ["c", "1", "2", "3"]...]

split and renamed arrays...

array1=["a", "1", "2", "3"]
array2=["b", "1", "2", "3"] 
array3=["c", "1", "2", "3"]...

I hope that makes sense... thanks Frank

Upvotes: 1

Views: 307

Answers (2)

user2398029
user2398029

Reputation: 6937

The only way I see to do quite literally what you are looking for is:

array=[["a", "1", "2", "3"], ["b", "1", "2", "3"],  ["c", "1", "2", "3"]]

array.each_with_index do |element, i|
  instance_variable_set "@array#{i + 1}", element
end

puts @array1 # => ["a", "1", "2", "3"]
puts @array2 # => ["b", "1", "2", "3"]

But of course, this is very ugly. Unless you absolutely need to do this, you should find a way to use your array without converting it to a list of variables. You shouldn't normally need to convert it to a hash, either - that's just converting one indexing style to another indexing style, and isn't giving you any added functionality.

Interestingly, note that this will not work, because eval (and the each block) have their own scope, which is not shared with the top-level scope:

array.each_with_index do |element, i|
  eval("array#{i + 1} = element")
end

puts array1 # => NameError

Upvotes: 1

mu is too short
mu is too short

Reputation: 434745

You could do some fancy-pants stuff to create a bunch of variables to hold the sub-arrays but then you'd have to do more confusing fancy-pants stuff to work the new variables. Whenever you think you want to dynamically create a bunch of variables, you usually want to create a Hash as a little portable namespace:

arrays = Hash[array.inject([]) { |m, a| m << ["array#{m.length + 1}", a] }]

That will give you this in arrays:

{
    "array1" => ["a", "1", "2", "3"],
    "array2" => ["b", "1", "2", "3"],
    "array3" => ["c", "1", "2", "3"]
}

and that's a lot easier to work with than a bunch of new variables whose names you won't know until runtime.

You could build the same structure with something simpler if you were so inclined:

arrays = { }
array.each_with_index { |a, i| arrays["array#{i + 1}"] = a }

Upvotes: 1

Related Questions