Ruby and Postgres are sorting slightly differently and this is causing subtle problems in my project. There's two issues: accented characters and spaces. It looks like Ruby is sorting ASCII-betically and Postgres is sorting with the proper Unicode collation algorithm.
Heroku Postgres 11.2. Database collation is en_US.UTF-8.
psql (11.3, server 11.2 (Ubuntu 11.2-1.pgdg16.04+1))
...
=> select 'quia et' > 'qui qui';
?column?
----------
f
(1 row)
=> select 'quib' > 'qüia';
?column?
----------
t
(1 row)
Ruby 2.4.4 on Heroku.
Loading production environment (Rails 5.2.2.1)
[1] pry(main)> 'quia et' > 'qui qui'
=> true
[2] pry(main)> 'quib' > 'qüia'
=> false
[3] pry(main)> ENV['LANG']
=> "en_US.UTF-8"
I can fix the handling of accented characters, but I can't get Ruby to do spaces correctly. For example, here's how they sort the same list.
Postgres: ["hic et illum", "quia et ipsa", "qui qui non"]
Ruby: ["hic et illum", "qui qui non", "quia et ipsa"]
I've tried the icunicode gem:
array.sort_by {|s| s.unicode_sort_key}
This handles accented characters, but does not do spaces correctly.
How do I get Ruby to sort using the Unicode collation algorithm?
UPDATE A more comprehensive example is found in Unicode® Technical Standard #10. These are in the correct order.
[
"di Silva Fred",
"diSilva Fred",
"disílva Fred",
"di Silva John",
"diSilva John",
"disílva John"
]