0

I want to transform the array

[[:name1, :value1], [:name2, :value2]]

to array

[[:value1, :name1], [:value2, :name2]]

What is the best way to do this?

1
  • You just need to swap each pair? What have you tried? There's many ways of going about this, and "best" is subjective. Commented Apr 18, 2017 at 14:25

3 Answers 3

6

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.

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

Comments

3

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]]

Comments

0

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]]

1 Comment

This solution expect all names and values are unique.

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.