E
E
eldar_web2016-06-20 11:20:58
Ruby on Rails
eldar_web, 2016-06-20 11:20:58

How can you sort a hash by a single condition in Ruby?

For example, there is a list hash:

list[
{ "plan": 100, 'present': 40 }
{ "plan": 100, 'present': 85 }
{ "plan": 100, 'present': 60 }
]

How can one sort in such a way that when the value of present is closer to plan in numerical value, so that it is higher? In our case, the second must be first, the third must be second, and the first must be last.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2016-06-21
@eldar_web

list.sort { |a,b| a['plan']-a['present'] <=> b['plan']-b['present'] }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question