6

How can I sort an array of accented words by the every letter in reference to variable alpha. The code below only reference alpha for the first letter so I am unable to get "ĝusti", "ĝusti vin","ĝuspa" to sort correctly.

I need the code to sort the words like this:

["bonan matenon", "ĉu vi parolas esperanton","ĝuspa", "ĝusti", "ĝusti vin",  "mi amas vin", "pacon"]

def alphabetize(phrases)
    alpha = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz".split(//)

    phrases.sort_by { |phrase|      
    alpha.index(phrase[0])  
    }
    end

alphabetize(["mi amas vin", "bonan matenon", "pacon", "ĉu vi parolas esperanton", "ĝusti", "ĝusti vin","ĝuspa"])
perror
  • 7,071
  • 16
  • 58
  • 85
hannaminx
  • 63
  • 4

2 Answers2

13

You could use the i18n gem like this:

# encoding: UTF-8
require 'i18n'
I18n.enforce_available_locales = false

a = ["bonan matenon", "ĉu vi parolas esperanton","ĝuspa", "ĝusti", "ĝusti vin",  "mi amas vin", "pacon"]
b = a.sort_by { |e| I18n.transliterate e }
puts b

gives

bonan matenon
ĉu vi parolas esperanton
ĝuspa
ĝusti
ĝusti vin
mi amas vin
pacon
peter
  • 41,770
  • 5
  • 64
  • 108
7

The fix is quite obvious: instead of just returning the first character's index, map all characters to their respective index:

def alphabetize(phrases)
  alpha = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz".chars

  phrases.sort_by do |phrase|
    phrase.chars.map { |c| alpha.index(c) }
  end
end

puts alphabetize(["mi amas vin", "bonan matenon", "pacon", "ĉu vi parolas esperanton", "ĝusti", "ĝusti vin","ĝuspa"])

Output:

bonan matenon
ĉu vi parolas esperanton
ĝuspa
ĝusti
ĝusti vin
mi amas vin
pacon

To speed up index lookup, you could use a hash:

alpha = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz".each_char.with_index.to_h
#=> {"a"=>0, "b"=>1, "c"=>2, ..., "v"=>26, "z"=>27}

and call alpha[c] instead of alpha.index(c)

Stefan
  • 109,145
  • 14
  • 143
  • 218
  • undefined method `to_h' for # – peter Feb 06 '15 at 17:20
  • can you explain how sort_by is working here because array is returned from map then how does sort_by uses that array to sort ? – Muhammad Umer Jul 31 '15 at 02:34
  • last time i checked i can't just compare arrays – Muhammad Umer Jul 31 '15 at 02:40
  • 2
    @MuhammadUmer of course you can compare arrays. From [`Array#<=>`](http://ruby-doc.org/core-2.2.2/Array.html#method-i-3C-3D-3E): *"Arrays are compared in an “element-wise” manner; the first element of ary is compared with the first one of other_ary using the <=> operator, then each of the second elements, etc…"* – Stefan Jul 31 '15 at 08:33