Ad
  • Default User Avatar

    sort_by uses an unstable quicksort so any chars being sorted by the size of the ordering string are not quaranteed to retain their position among other unsorted chars.

  • Custom User Avatar

    Yes, you are correct. But why the heck does it do that?

  • Custom User Avatar

    This does not always return the correct result. For some input strings, it changes relative positions of the characters that are not in the ordering string.

    def sort_string(str,ordering)
    str.chars.sort_by { |c| ordering.index(c) || ordering.size}
    end

    p sort_string("bananapxcgsdfhjd", "anb").join("")
    p "aaannbpxcgsdfhjd"

    the sort_string method results in "aaannbcxp..." instead of "aaannbpxc...". I am running ruby 2.2.0p0