-3

I have an array like this:

array = ["git-hw-abcd", "svn-hw", "svn-hw-design","git-hw"]

If I do array.sort I would basically get an ascending sort like this

["git-hw", "git-hw-abcd", "svn-hw", "svn-hw-design"]

Would like to sort the array by the values "svn-hw" and "git-hw" to appear as the first and second elements of the array so that I would get:

[ "svn-hw","git-hw",... then the rest of the values]

Any help would be appreciated.

4
  • 1
    write a block for your sort. ruby-doc.org/core-2.0/Array.html#method-i-sort
    – oldergod
    May 30, 2013 at 6:39
  • 3
    What exact sort criteria do you want? Why does git-hw-abcd appear before svn-hw-design?
    – Arie Xiao
    May 30, 2013 at 6:41
  • How does a four-element array become a three-element array by sort?
    – sawa
    May 30, 2013 at 7:46
  • Edited my post. There was a typo.
    – Supersonic
    May 30, 2013 at 7:57

3 Answers 3

2

Try this

* sorting on length(as sort criteria is not specified)

["git-hw-abcd", "svn-hw", "svn-hw-design","git-hw"].sort{|a,b| a.length <=> b.length}

It returns

["git-hw", "svn-hw", "git-hw-abcd", "svn-hw-design"]
2

array.sort{|a,b| a.split("-h")[1]<=>b.split("-h")[1]}

this is what you want

@Hivltg

try the length order using this :array= [ "svn-hw", "git-hw-abcd","git-hw", "svn-hw-design", "git-hw-bassics"]

you will find out the problem.

3
  • Thanks for your response but split wouldn't work effeciently as it would throw an error if "-" is not present in the array.
    – Supersonic
    May 30, 2013 at 7:59
  • If your array is not as a fixed pattern ,then there is no way to perfectly solve your problem. May 30, 2013 at 8:04
  • And just order by length won't affect when there is a string like 'xxx-hw-aaaaaaaaaaaaaa',it should before 'xxx-hw-b', am I right? or you do mean 'order by length' May 30, 2013 at 8:07
1

Not exactly sure how you're ordering, but here's an example of using a block to sort

array.sort{|a,b| a[4..-1] <=> b[4..-1]}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.