简体   繁体   中英

ruby - Putting elements of an array of arrays in a variable by index

I have this array of arrays :

array = [["z1", "y1", "x1"], ["z2", "y2", "x2"], ["z3", "y3", "x3"], ["z4", "y4" , "x4"]]

I want to be able to retrieve elements of the array within the bigger array by an index and putting them in a variable.
For example for the index 1 the output should be :

output = [["y1"], ["y2"], ["y3"], ["y4"]]

I want also after that to be able to push these results to form a new array. In other words, I want to re-order the elements of the array (if you could find a better solution than retrieving and pushing).

Example :

output_x = [["x1"], ["x2"], ["x3"], ["x4"]]

output_y = [["y1"], ["y2"], ["y3"], ["y4"]]

output_z = [["z1"], ["z2"], ["z3"], ["z4"]]

So the final result should look like :

result = [["x1", "y1", "z1"], ["x2", "y2", "z2"], ["x3", "y3", "z3"], ["x4", "y4" , "z4"]]

I really want to find a solution for this. Thank you

PS : x,y and z are coordinates. Forget about sort ing them

You just want Array#transpose , which is the inverse of Array#zip :

[["z1", "y1", "x1"],
 ["z2", "y2", "x2"],
 ["z3", "y3", "x3"],
 ["z4", "y4" , "x4"]].transpose

=> [["z1", "z2", "z3", "z4"],
    ["y1", "y2", "y3", "y4"],
    ["x1", "x2", "x3", "x4"]]

From there, it's easy enough to split those into individual arrays. If you just want to translate the arrays into XYZ (rather than ZYX), then you may perhaps want to just map the reversed arrays:

[["z1", "y1", "x1"],
 ["z2", "y2", "x2"],
 ["z3", "y3", "x3"],
 ["z4", "y4" , "x4"]].map(&:reverse)
=> [["x1", "y1", "z1"],
    ["x2", "y2", "z2"],
    ["x3", "y3", "z3"],
    ["x4", "y4", "z4"]] 

You could also just map an arbitrary order. For example, to map from your ZYX to XZY, you would use:

coordinates.map {|c| [c[2], c[0], c[1]] }

You can do a sort on each element in array like this

array.each do |e|
  e.sort!
end

if you run the code above, your array would look like what you want for

result = [["x1", "y1", "z1"], ["x2", "y2", "z2"], ["x3", "y3", "z3"], ["x4", "y4" , "z4"]]

For more information about sort, check here

Update

According to your comment below, you have coordinates in each sub array. Since the order right now is z, y, x , and you want them in x, y, z . Reversing the elements in the array would do the trick.

array.each do |e|
  e.reverse!
end

For more information about reverse, check here

If you're just looking for the final outcome:

array  = [["z1", "y1", "x1"], ["z2", "y2", "x2"], ["z3", "y3", "x3"], ["z4", "y4" , "x4"]]
option = []

array.each do |item|
  option << item.reverse
end

puts option.inspect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM