Ruby Sort_By Multiple Fields

ruby sort_by multiple fields

Your sorting works correctly in MRI Ruby 1.8.7, 1.9.3, and 2.0.0:

Item = Struct.new(:name, :dir, :sort_dir)

entries = [Item.new('favicon.ico', false, 1), Item.new('bin', true, 0),
Item.new('web.config', false, 1), Item.new('images', true, 0),
Item.new('global.asax', false, 1), Item.new('content', true, 0)]

entries.sort_by{|e| [e.sort_dir, e.name]}
# => [#<struct Item name="bin", dir=true, sort_dir=0>,
# #<struct Item name="content", dir=true, sort_dir=0>,
# #<struct Item name="images", dir=true, sort_dir=0>,
# #<struct Item name="favicon.ico", dir=false, sort_dir=1>,
# #<struct Item name="global.asax", dir=false, sort_dir=1>,
# #<struct Item name="web.config", dir=false, sort_dir=1>]

Have you tried outputting the result of your sort_by to a console? I'm not familiar with the render json: portion of your code, but perhaps that's where things are going wrong. My best guess is that somehow in the conversion to JSON (if that's what it does) the sorting is getting messed up.

My other idea is that perhaps you expect sort_by to modify entries; it does not. If you want entries itself to be sorted after the call, use sort_by! (note the ! at the end of the method name).

Update: It looks like the issue is that you want a case-insensitive search. Simply adding upcase should do the trick:

entries.sort_by{|e| [e.sort_dir, e.name.upcase]}

Ruby sort by multiple fields and multilple directions for different data types

Very interesting problem. I also think the sort_by method would be most helpful.
My solution (for numerical values only) works like this:

DIRECTION_MULTIPLIER = { asc: 1, desc: -1 }

def multi_sort(items, order)
items.sort_by do |item|
order.collect do |key, direction|
item[key]*DIRECTION_MULTIPLIER[direction]
end
end
end

# ... items ...
multi_sort(items, a_sort: :asc, display_sort: :desc)

The idea is to construct a list for each item passed by sort_by. This list consists out of all values for which a sort order was given. Hence, we use that Ruby knows that [1,2] is smaller than [1,3] but greater than [0,0].

An interesting part to note is that the last parameters for the function will be passed as one Hash and the order of these hash pairs will be maintained. This "ordered" behavior in Hashes is not necessarily true for all languages, but the Ruby documentation states: Hashes enumerate their values in the order that the corresponding keys were inserted.

-- Edit for more generality --

Since, chamnap asked for a more general solution which works with arbitrary data types and nil, here a more comprehensive solution which relies on the <=> operator:

require 'date'
DIRECTION_MULTIPLIER = { asc: 1, desc: -1 }

# Note: nil will be sorted towards the bottom (regardless if :asc or :desc)
def multi_sort(items, order)
items.sort do |this, that|
order.reduce(0) do |diff, order|
next diff if diff != 0 # this and that have differed at an earlier order entry
key, direction = order
# deal with nil cases
next 0 if this[key].nil? && that[key].nil?
next 1 if this[key].nil?
next -1 if that[key].nil?
# do the actual comparison
comparison = this[key] <=> that[key]
next comparison * DIRECTION_MULTIPLIER[direction]
end
end
end

I am using the sort method. The block gets called each time the sort function needs to compare to elements. The block shall return -1, 0 or 1 (smaller, equal or higher in the order) for the respective pair. Within this sort block I am going through the order hash which contains the key and the direction for a hash value in items. If we have found an earlier difference in order (e.g. the first key was higher) we just return that value. If the past comparisons came up with equal order, we use the <=> operator to compare the two elements passed to the sort block (and multiply the result it with -1 if we want descending order). The only annoying thing is to deal with nil values, which adds the three lines above the actual comparison.

And here my test code:

items = [ {n: 'ABC  ', a:   1, b: Date.today+2},
{n: 'Huhu ', a: nil, b: Date.today-1},
{n: 'Man ', a: nil, b: Date.today},
{n: 'Woman', a: nil, b: Date.today},
{n: 'DEF ', a: 7, b: Date.today-1}]
multi_sort(items, b: :asc, a: :desc, n: :asc)

On a more general note: Since the logic for sorting becomes a little more complicated, I would wrap the data in actual objects with attributes. Then you could overwrite the <=> operator as seen here.

Ruby sort by multiple values?

a.sort { |a, b| [a['foo'], a['bar']] <=> [b['foo'], b['bar']] }

How do I sort in ruby/rails on two fields?


The best way would be to have your database do it, but if you want to use Ruby:

@games = @data.sort_by {|x| [x.game_date, x.team] }

The sorting behaviour of Array is to sort by the first member, then the second, then the third, and so on. Since you want the date as your primary key and the team as the second, an array of those two will sort the way you want.

Multiple field sort_by combination of reverse and not

data = [{:score=>100.0, :matches_count=>2, :name=>"DAV"},
{:score=>100.0, :matches_count=>1, :name=>"SAN"},
{:score=>100.0, :matches_count=>1, :name=>"PAS"},
{:score=>110.0, :matches_count=>1, :name=>"PAR"},
{:score=>100.0, :matches_count=>1, :name=>"NUE"}]

data.sort_by{ |h| [-h[:score], -h[:matches_count], h[:name]] }
#=> [{:score=>110.0, :matches_count=>1, :name=>"PAR"},
# {:score=>100.0, :matches_count=>2, :name=>"DAV"},
# {:score=>100.0, :matches_count=>1, :name=>"NUE"},
# {:score=>100.0, :matches_count=>1, :name=>"PAS"},
# {:score=>100.0, :matches_count=>1, :name=>"SAN"}]

You could also use Array#sort, which does not require that values to be sorted on in descending order be numeric, so long as they are comparable, that is, so long as they respond to the method :<=>.

data.sort do |t1, t2|
case t1[:score] <=> t2[:score]
when -1
1
when 1
-1
else
case t1[:matches_count] <=> t2[:matches_count]
when -1
1
when 1
-1
else
t1[:name] <=> t2[:name]
end
end
end
#=> <as above>

How does `sort_by` work with multiple fields?

The problem here is nothing particularly about multiple comparison. If you compare arrays, each of the elements will be compared to the corresponding one in another array. If those values sometimes take numerical values, then they always have to be numerals. Numerals cannot be compared to nil, and doing so will raise an error. Defaulting them to zero is to ensure they are numerals. As long as you default them to a numeral, it will not raise an error. The particular choice of zero was based on where you want to position the entries with the missing values; you could have chosen infinity, negative infinity, etc for different results.

Sort array of active records by multiple columns

A good way is to use sort and <=> and nonzero? like this:

jobs.sort{|a,b| 
(a.organization <=> b.organization).nonzero? ||
(b.created_at <=> a.created_at)
}

This code says:

  1. Compare A and B by organization.
  2. If they differ, then we have our answer.
  3. If they are the same, then we need to do more.
  4. Compare B and A by time. (Note B & A are in reverse order)
  5. If they differ, then we have our answer.
  6. If they are the same, then the sort order doesn't matter. (Ruby sort is "unstable")

Example code independent of ActiveRecord:

require 'time'
require 'ostruct'

jobs = [
OpenStruct.new(_id: 1, created_at: Time.parse("2014-07-15 19:18:40 UTC"), organization: "Acme Inc"),
OpenStruct.new(_id: 3, created_at: Time.parse("2014-05-20 09:27:38 UTC"), organization: "Baxter"),
OpenStruct.new(_id: 2, created_at: Time.parse("2014-11-25 12:21:00 UTC"), organization: "Wizard"),
OpenStruct.new(_id: 3, created_at: Time.parse("2015-01-15 07:20:10 UTC"), organization: "Baxter")
]

Rails Sort Array By Two Columns

Use sort_by:

surveys.sort_by { |survey| [survey.length, survey.cost] }

If you want to control asc vs desc, just multiply by -1:

surveys.sort_by { |survey| [-1 * survey.length, survey.cost] }

This should work for both regular array of objects or ActiveRecord::Relation



Related Topics



Leave a reply



Submit