6

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

Charlie Egan
  • 4,878
  • 6
  • 33
  • 48

1 Answers1

8

You can use this syntax:

my_array = ["123", "22", "1"]
sorted = my_array.sort_by &.size
puts sorted
=> ["1", "22", "123"]
dimid
  • 7,285
  • 1
  • 46
  • 85
  • 6
    Check http://crystal-lang.org/2013/09/15/to-proc.html it explains some of the reasons `&.` plays nicer than `&:` – Brian J Cardiff Feb 22 '16 at 12:08
  • 1
    @BrianJCardiff I wonder if this syntax is going to change because of the new [lonely operator](http://ruby-operators.herokuapp.com/#/lonely) – dimid Feb 23 '16 at 08:13
  • 1
    @dimid, I don't see the `&.` going away any time soon. we like how it feels. – Brian J Cardiff Mar 29 '16 at 18:59
  • @BrianJCardiff I feel like it's an unnecessary breaking change from ruby to crystal, both syntaxes could be supported – Dorian Jul 06 '21 at 13:32