-1

I have a web service that is supposed to return a list of translation keys in alphabetical order. But it actually does not do so when underscores are involved. It sends the keys in this order:

en.orders
en.order_mail

whereas I expect the order to be this:

en.order_mail
en.orders

which is the order given by sorting strings:

["en.orders", "en.order_mail"].sort
# => ["en.order_mail", "en.orders"]

I'm not sure how to handle this. I've tried removing underscores, replacing them with other characters etc. but it always has some unwanted side effects.

Is there a way to treat the underscore differently when sorting arrays?

5
  • Try to create your own sort implementation like here. Commented Mar 5, 2018 at 14:11
  • Not clear what you mean. What are translation keys? Commented Mar 5, 2018 at 14:40
  • How does your service sort the keys then, if it results in this order? Commented Mar 5, 2018 at 14:48
  • 1
    "treat the underscore differently" – how? And what are those unwanted side effects when replacing it? Commented Mar 5, 2018 at 15:09
  • Those are paths to YAML translation keys. The service claims to return the keys in an alphabetical order. This is true until an underscore comes into play. They claim "en.orders" comes BEFORE "en.order_mail" but when you sort them in ruby, the order is reversed. Does this make my question clearer? Commented Mar 5, 2018 at 16:12

1 Answer 1

2

They claim "en.orders" comes BEFORE "en.order_mail""

How do they back this claim? "_" is ASCII 95 and "s" is ASCII 115. Same in UTF-8. So the underscore is rightly sorted before the "s". I don't see how it could be otherwise.

However, it is the other way around for upper-case letters.

puts ["en.orders", "en.order_mail"].map(&:upcase).sort
# >> EN.ORDERS
# >> EN.ORDER_MAIL

Armed with this knowledge you can match their sort order by upcasing, sorting, downcasing (if that is what you want to do).

Or simply use sort_by, which can sort your array not by its elements, but by a function of its elements (thanks for reminding @steenslag)

puts ["en.orders", "en.order_mail"].sort_by(&:upcase)
# >> en.orders
# >> en.order_mail
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.