I want to transform the array
[[:name1, :value1], [:name2, :value2]]
to array
[[:value1, :name1], [:value2, :name2]]
What is the best way to do this?
I want to transform the array
[[:name1, :value1], [:name2, :value2]]
to array
[[:value1, :name1], [:value2, :name2]]
What is the best way to do this?
Various options (each version followed by short-hand sugar):
# Create a new array of swapped elements
my_array = my_array.map{ |a| a.reverse }
my_array = my_array.map(&:reverse)
# Mutate the existing array with swapped elements
my_array.map!{ |a| a.reverse }
my_array.map!(&:reverse)
# Mutate the elements in the existing array
my_array.each{ |a| a.reverse! }
my_array.each(&:reverse!)
The first option is the 'safest', insofar as no existing arrays are modified (in case you have other references to them that should not be changed).
The second option is roughly the same as the first, unless you had two references to my_array and wanted one of them unswapped.
The third option is the most 'destructive'; every reference to the pairwise elements will be changed. However, it's also the most memory-efficient, because no new arrays are created.
Just-for-fun answer (rotate the matrix like rubik's cube):
array = [[:name1, :value1], [:name2, :value2]]
array.transpose # [[:name1, :name2], [:value1, :value2]]
.reverse # [[:value1, :value2], [:name1, :name2]]
.transpose
#=> [[:value1, :name1], [:value2, :name2]]
One more (not as funny and obvious, but still possible) way:
array.inject(&:zip).reverse.inject(&:zip)
#=> [[:value1, :name1], [:value2, :name2]]
One more way is to use to_h to_a:
array = [[:name1, :value2], [:name2, :value2]]
array.to_h # {name1: :value1, name2: :value2}
.invert # {value1: :name1, value2: :name2}
.to_a # [[:value1, :name1], [:value2, :name2]]