Search code examples
arrayscrystal-lang

Is there a simple way to sort an array in Crystal?


I'm new to Crystal and I find it fun to learn and work with. What's a simple and quick way to sort an array?


Solution

  • Without knowing what your Array actually contains i assume it's an Array(Int32) (array of integers).

    You can easily sort an array of integers like

    [4, 7, 2].sort { |x, y| y <=> x } # => [7, 4, 2]
    

    Check the array spec in Crystal core for more info https://github.com/crystal-lang/crystal/blob/bf6b743aa7649ed3ecc92dd06fde21f88460720a/spec/std/array_spec.cr#L998-L1047