views:

119

answers:

5

I have array

a = ["aaa", "bee", "cee", "dee"]

I want have new array with sort as like:

a = ["cee", "aaa", "dee", "bee"]

Please help me. thanks.

+3  A: 
a = ["aaa", "bee", "cee", "dee"]
b = [a[2], a[0], a[3], a[1]]

Sorry, couldn't resist. Seriously, please explain this strange "sorting".

DarkDust
+1 because it's fast :)
KARASZI István
+2  A: 

you can give a block for the Array.sort method to have a custom sorting, like this:

[ "aaa", "bee", "cee", "dee"].sort do |x,y|
   # do the actual custom sorting
end
KARASZI István
A: 

Going from your comments, you want to sort an array with names Blueray,DVD, ipod as DVD, Bluray, ipod.

An array is by definition order-based, unlike a hash. So if possible, you could just redefine your array in the correct order.

Otherwise i would suggest using a domain-table, with an id, name and description. Just make sure you insert the rows in the correct order (the id is the order), and all your select-boxes can use these options sorted as you want. Also using a domain-table you can then just refer to the video-type by id.

nathanvda
A: 
a = ["aaa", "bee", "cee", "dee"]
a = [2, 0, 3, 1].map { |i| a[i] }
p a    # => ["cee", "aaa", "dee", "bee"]
Wayne Conrad
+1  A: 

Have a look at array intersection, e.g. [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]

The first of the two arrays determines the sorting of the elements. So, just use a predefined array ["DVD", "Blueray", "ipod"] and perform an intersection operation with the unsorted array on it: a = ["DVD", "Blueray", "ipod"] & a.

For example: a = ["DVD", "Blueray", "ipod"] & ["ipod", "DVD"] #=> ["DVD", "ipod"].

Very elegant and simple solution. Bonus: Invalid values are discarded without any exception or error or what ever. (Is it a bonus? Maybe!)

Flinsch
Not sure if this is what the OP needs, but i learned something new :)
nathanvda