Question: I have a hash as follows:

```
{
  :student_name => ['A', 'B', 'C'],
  :total_marks => [100, 25, 50]
}

```

I want to sort each value (array) of this hash by the order of the corresponding element in the value for `:total_marks` when this array is sorted. The resultant hash should look like this:

```
{
  :student_name => ['B', 'C', 'A'],
  :total_marks => [25, 50, 100]
}

```

What is a scalable solution? This hash can have many other attributes.

Answer: 
```
h = {:student_name=>["A", "B", "C"], :total_marks=>[100, 25, 50]}

indices = h[:total_marks].to_enum.with_index.sort_by(&:first).map(&:last)
h.each{|_, v| v.replace(v.values_at(*indices))}
#=> {:student_name=>["B", "C", "A"], :total_marks=>[25, 50, 100]}

```
Given the design of your hash, we need to first pair student and marks together.

```
h = {
    :student_name => ['A', 'B', 'C'],
    :total_marks => [100, 25, 50]
}

student_array = h[:student_name]
marks_array = h[:total_marks]

student_marks = []
student_array.each_with_index {|student, idx| student_marks << [student, marks_array[idx]]}
p student_marks  # Prints [["A", 100], ["B", 25], ["C", 50]]

```

So, now that we have a array where student and marks are paired, we will sort the above array using second element of sub-array

```
sorted = student_marks.sort {|i, j| i[1] <=> j[1]}
p sorted # Prints [["B", 25], ["C", 50], ["A", 100]]

```

Now that we have sorted student and marks, we will use it to update the original hash with sorted values

```
h[:student_name] = sorted.collect {|i| i[0]}
h[:total_marks]= sorted.collect {|i| i[1]}
p h

```

Finally, we have the result

```
{:student_name=>["B", "C", "A"], :total_marks=>[25, 50, 100]}

```

PS: Look at [sawa's answer](https://stackoverflow.com/questions/32166359/ruby-sorting-array-of-each-attribute-of-a-hashmap-wrt-one-attribute-of-the-has/32166420#32166420) for compact & elegant way of solving this.