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: 
If you want the code to be simple and involve the least amount of indirection, I'd recommend holding the student's name and total mark together, rather than as parallel arrays. This way, you can add extra fields without then having to rewrite your sort routine (which would otherwise have to now resort *another* parallel array for the new field).

```
ExamResult = Stuct.new(:student_name, :total_mark)

exam_results = [
    ExamResult.new('Adam', '25'),
    ExamResult.new('Sajani', '100'),
    ExamResult.new('Sawa', '50')
]

# Sort
exam_results.sort_by &:total_mark

```

As for scalability, that will *heavily* depend on what *kind* of scalability you need. The above method will likely handle hundreds of thousands of `ExamResult`'s without much effort. If you want to do *millions* upon *millions* or exam results without overloading your memory then you're going to need a better way of sorting the grades and streaming exam results anyway, regardless of how you've structured it.
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.