awenkhh
awenkhh

Reputation: 6111

How to sort an Array of Arrays in Ruby where the first elements is a String

The question is how to sort an Array of Arrays with the following structure:

status = 
 [["Wartend", :pending],
  ["Schufa Check", :schufa_check],
  ["Schufa Key existiert", :schufa_person_key_exists],
  ["LottoIdent", :lotto_ident],
  ["IBAN existiert", :iban_exists],
  ["E-Mail Bestätigung", :email_validation],
  ["SMS Bestätigung", :mobile_validation],
  ["Aktiv", :active],
  ["gesperrt", :locked],
  ["ausgeschlossen", :locked_out],
  ["werden gelöscht", :marked_for_deletion]]

The result should be this:

[["Aktiv", :active], 
 ["ausgeschlossen", :locked_out], 
 ["E-Mail Bestätigung", :email_validation], 
 ["gesperrt", :locked], 
 ["IBAN existiert", :iban_exists], 
 ["LottoIdent", :lotto_ident], 
 ["Schufa Check", :schufa_check], 
 ["Schufa Key existiert", :schufa_person_key_exists], 
 ["SMS Bestätigung", :mobile_validation], 
 ["Wartend", :pending], 
 ["werden gelöscht", :marked_for_deletion]]

Upvotes: 0

Views: 1117

Answers (2)

steenslag
steenslag

Reputation: 80065

p status.sort_by{|ar| ar.first.downcase}
# =>[["Aktiv", :active], ["ausgeschlossen", :locked_out], ["E-Mail Bestätigung", :email_validation], ["gesperrt", :locked], ["IBAN existiert", :iban_exists], ["LottoIdent", :lotto_ident], ["Schufa Check", :schufa_check], ["Schufa Key existiert", :schufa_person_key_exists], ["SMS Bestätigung", :mobile_validation], ["Wartend", :pending], ["werden gelöscht", :marked_for_deletion]]

Upvotes: 5

awenkhh
awenkhh

Reputation: 6111

A common error is to forget, that the String (in each Array at position a[0]) is upper or lowercase. Naturally the sorting will result in something like:

 "Aktiv",  
 "E-Mail Bestätigung",  
 "IBAN existiert",  
 "LottoIdent",  
 ...,  
 "SMS Bestätigung",  
 "ausgeschlossen",    
 "gesperrt"  

So the solution is to use the common Ruby sort method with a block and to downcase the values at position a[0]:

status.sort{|x,y| x[0].downcase <=> y[0].downcase}

Upvotes: 2

Related Questions