Shorthand block syntax in Crystal
Asked Answered
P

1

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

Prothesis answered 22/2, 2016 at 11:31 Comment(0)
F
8

You can use this syntax:

my_array = ["123", "22", "1"]
sorted = my_array.sort_by &.size
puts sorted
=> ["1", "22", "123"]
Forsyth answered 22/2, 2016 at 11:46 Comment(4)
Check crystal-lang.org/2013/09/15/to-proc.html it explains some of the reasons &. plays nicer than &:Rourke
@BrianJCardiff I wonder if this syntax is going to change because of the new lonely operatorForsyth
@dimid, I don't see the &. going away any time soon. we like how it feels.Rourke
@BrianJCardiff I feel like it's an unnecessary breaking change from ruby to crystal, both syntaxes could be supportedFloria

© 2022 - 2024 — McMap. All rights reserved.