Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Sorting an Array, skipping the first element

I want to sort an Array of Arrays of Strings by the first String skipping the first Array but I just don't have an idea how to do it using the build-in sort method. I could copy the whole array without the first element and sort the resutling Array then but isn't there a more elegant way to do this?

ar = [["zzzz", "skip", "this"], ["EFP3","eins","eins"], ["EFP10","zwei","zwei"], ["EFP1","drei","drei"]]
ar.sort!{ |a,b|
  if a == ar.first   # why doesn't 
    next             # this
  end                # work ?

  # compare length, otherwise it would be e.g. 10 < 3
  if a[0].length == b[0].length
    a[0] <=> b[0]
  else
    a[0].length <=> b[0].length
  end
}

I want to have the result like this:

["zzzz", "skip", "this"], ["EFP1","drei","drei"], ["EFP3","eins","eins"], ["EFP10","zwei","zwei"]

sortet by "EFP#"

edit: I'm using Ruby 1.8, if it matters.

like image 742
SimonH Avatar asked Jun 06 '26 20:06

SimonH


1 Answers

ar[1..-1].sort { whatever you want }
like image 148
asiniy Avatar answered Jun 09 '26 10:06

asiniy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!