Search code examples
crystal-lang

Shorthand block syntax in Crystal


Is it possible to use a shorthand for blocks in Crystal, e.g.

my_array.sort_by(&:size)

This attempt returns an error:

... expected a function type, not Symbol


Solution

  • You can use this syntax:

    my_array = ["123", "22", "1"]
    sorted = my_array.sort_by &.size
    puts sorted
    => ["1", "22", "123"]