1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
|
# Examples taken from http://crystal-lang.org/docs/
# Copyright 2012-2016 Manas Technology Solutions.
require "http/server"
server = HTTP::Server.new(8080) do |context|
context.response.content_type = "text/plain"
context.response.print "Hello world! The time is #{Time.now}"
end
puts "Listening on http://0.0.0.0:8080"
server.listen
module HTTP
class RequestHandler
end
end
alias NumericValue = Float32 | Float64 | Int32 | Int64
enum Time::DayOfWeek
end
$global_greeting = "Hello world"
class Greeting
@@default_greeting = "Hello world"
def initialize(@custom_greeting = nil)
end
def print_greeting
greeting = @custom_greeting || @@default_greeting
puts greeting
end
end
LUCKY_NUMBERS = [3, 7, 11]
DOCUMENTATION_URL = "http://crystal-lang.org/docs"
module Scorecard
class Parser
def parse(score_text)
begin
score_text.scan(SCORE_PATTERN) do |match|
handle_match(match)
end
rescue err : ParseError
# handle error ...
end
end
end
end
module Money
CURRENCIES = {
"EUR" => 1.0,
"ARS" => 10.55,
"USD" => 1.12,
"JPY" => 134.15,
}
class Amount
getter :currency, :value
def initialize(@currency, @value)
end
end
class CurrencyConversion
def initialize(@amount, @target_currency)
end
def amount
# implement conversion ...
end
end
end
i = 0
while i < 10
proc = ->(x : Int32) do
spawn do
puts(x)
end
end
proc.call(i)
i += 1
end
Fiber.yield
# A buffered channel of capacity 2
channel = Channel(Int32).new(2)
spawn do
channel.send(1)
channel.send(2)
channel.send(3)
end
3.times do |i|
puts channel.receive
end
class MyDictionary(K, V)
end
MyBox.new(1) #:: MyBox(Int32)
MyBox.new("hello") #:: MyBox(String)
module Moo(T)
def t
T
end
end
class Foo(U)
include Moo(U)
def initialize(@value : U)
end
end
foo = Foo.new(1)
foo.t # Int32
class Parent(T)
end
class Int32Child < Parent(Int32)
end
class GenericChild(T) < Parent(T)
end
class Person
end
a = 1
ptr = pointerof(a)
ptr[100_000] = 2 # undefined behaviour, probably a segmentation fault
alias Int32OrString = Int32 | String
alias Int32OrNil = Int32?
alias Int32OrNil_ = Int32 | ::Nil
alias Int32Ptr = Int32*
alias Int32Ptr_ = Pointer(Int32)
alias Int32_8 = Int32[8]
alias Int32_8_ = StaticArray(Int32, 8)
alias Int32StringTuple = {Int32, String}
alias Int32StringTuple_ = Tuple(Int32, String)
alias Int32ToString = Int32 -> String
alias Int32ToString_ = Proc(Int32, String)
alias ProcThatReturnsInt32 = -> Int32
alias Int32AndCharToString = Int32, Char -> String
alias ComplexProc = (Int32 -> Int32) -> String
def foo(x : Int32)
"instance"
end
def foo(x : Int32.class)
"class"
end
foo 1 # "instance"
foo Int32 # "class"
class Parent
end
class Child1 < Parent
end
class Child2 < Parent
end
ary = [] of Parent.class
ary << Child1
ary << Child2
# Same as not specifying a restriction, not very useful
def foo(x : _)
end
# A bit more useful: any two arguments Proc that returns an Int32:
def foo(x : _, _ -> Int32)
end
#alias SameAsInt32 = typeof(2)
#alias Int32OrString_ = typeof(1, "a")
class Person
def initialize(name)
@name = name
@age = 0
end
def name
@name
end
def age
@age
end
end
john = Person.new "John"
peter = Person.new "Peter"
john.name #=> "John"
john.age #=> 0
peter.name #=> "Peter"
class Person
def self.new(name)
instance = Person.allocate
instance.initialize(name)
instance
end
end
if a.is_a?(String)
# here a is a String
end
if b.is_a?(Number)
# here b is a Number
end
a = some_condition ? 1 : "hello"
# a : Int32 | String
if a.is_a?(Number)
# a : Int32
else
# a : String
end
if a.is_a?(String) && b.is_a?(Number)
# here a is a String and b is a Number
end
a.+(b)
struct Vector2
getter x, y
def initialize(@x, @y)
end
def +(other)
Vector2.new(x + other.x, y + other.y)
end
end
v1 = Vector2.new(1, 2)
v2 = Vector2.new(3, 4)
v1 + v2 #=> Vector2(@x=4, @y=6)
struct Vector2
def -
Vector2.new(-x, -y)
end
end
v1 = Vector2.new(1, 2)
-v1 #=> Vector2(@x=-1, @y=-2)
class MyArray
def [](index)
# ...
end
def [](index1, index2, index3)
# ...
end
def []=(index, value)
# ...
end
end
array = MyArray.new
array[1] # invokes the first method
array[1, 2, 3] # invokes the second method
array[1] = 2 # invokes the third method
array.[](1) # invokes the first method
array.[](1, 2, 3) # invokes the second method
array.[]=(1, 2) # invokes the third method
raise "OH NO!"
raise Exception.new("Some error")
class MyException < Exception
end
begin
raise MyException.new("OH NO!")
rescue ex : MyException
puts "Rescued MyException: #{ex.message}"
end
begin
# ...
rescue ex : MyException | MyOtherException
# only MyException or MyOtherException
rescue
# any other kind of exception
ensure
puts "Cleanup..."
end
def some_method
something_dangerous
rescue
# execute if an exception is raised
end
array = [1, 2, 3]
array[4] # raises because of IndexError
array[4]? # returns nil because of index out of bounds
def some_proc(&block : Int32 -> Int32)
block
end
x = 0
proc = ->(i : Int32) { x += i }
proc = some_proc(&proc)
proc.call(1) #=> 1
proc.call(10) #=> 11
x #=> 11
def add(x, y)
x + y
end
adder = ->add(Int32, Int32)
adder.call(1, 2) #=> 3
module Curses
class Window
end
end
Curses::Window.new
module ItemsSize
def size
items.size
end
end
class Items
include ItemsSize
def items
[1, 2, 3]
end
end
items = Items.new
items.size #=> 3
module Base64
extend self
def encode64(string)
# ...
end
def decode64(string)
# ...
end
end
Base64.encode64 "hello" #=> "aGVsbG8="
if some_condition
a = 1
else
a = "hello"
end
a_as_int = a as Int32
a_as_int.abs # works, compiler knows that a_as_int is Int32
ptr = Pointer(Int32).malloc(1)
ptr as Int8* #:: Pointer(Int8)
array = [1, 2, 3]
# object_id returns the address of an object in memory,
# so we create a pointer with that address
ptr = Pointer(Void).new(array.object_id)
# Now we cast that pointer to the same type, and
# we should get the same value
array2 = ptr as Array(Int32)
array2.same?(array) #=> true
a = 1
b = a as Int32 | Float64
b #:: Int32 | Float64
ary = [1, 2, 3]
# We want to create an array 1, 2, 3 of Int32 | Float64
ary2 = ary.map { |x| x as Int32 | Float64 }
ary2 #:: Array(Int32 | Float64)
ary2 << 1.5 # OK
class Person
def initialize(@name)
end
def name
@name
end
end
a = [] of Person
x = a.map { |f| f.name } # Error: can't infer block return type
a = [] of Person
x = a.map { |f| f.name as String } # OK
Person.new "John"
a = [] of Person
x = a.map { |f| f.name } # OK
loop do
do_something
break if some_condition
end
class Point
def initialize(@x, @y)
end
end
Point.new 1, 2
# 2 x Int32 = 2 x 4 = 8
instance_sizeof(Point) #=> 12
a = 1
while a < 5
a += 1
if a == 3
next
end
puts a
end
# The above prints the numbers 2, 4 and 5
lib C
# In C: double cos(double x)
fun cos(value : Float64) : Float64
fun getch : Int32
fun srand(seed : UInt32)
fun exit(status : Int32) : NoReturn
fun printf(format : UInt8*, ...) : Int32
end
C.cos(1.5) #=> 0.0707372
C.srand(1_u32)
a = 1
b = 2
C.printf "%d + %d = %d\n", a, b, a + b
lib LibSDL
fun init = SDL_Init(flags : UInt32) : Int32
end
lib LLVMIntrinsics
fun ceil_f32 = "llvm.ceil.f32"(value : Float32) : Float32
end
lib MyLib
fun my_fun(some_size : LibC::SizeT)
end
@[Link("pcre")]
lib LibPCRE
end
lib C
ifdef x86_64
alias SizeT = UInt64
else
alias SizeT = UInt32
end
fun memcmp(p1 : Void*, p2 : Void*, size : C::SizeT) : Int32
end
lib X
enum SomeEnum
Ten = 10
Twenty = 10 * 2
ThirtyTwo = 1 << 5
end
end
lib X
enum SomeEnum
A = 1_u32
end
end
X::SomeEnum::Zero #=> 0_i8
X::SomeEnum::Two #=> 2_i8
lib X
fun callback(f : Int32 -> Int32)
end
f = ->(x : Int32) { x + 1 }
X.callback(f)
X.callback ->(x) { x + 1 }
X.callback nil
lib LibFoo
fun store_callback(callback : ->)
fun execute_callback
end
LibFoo.store_callback ->{ raise "OH NO!" }
LibFoo.execute_callback
lib LibFoo
fun store_callback(callback : ->)
@[Raises]
fun execute_callback
end
@[Link("pcre")]
lib PCRE
INFO_CAPTURECOUNT = 2
end
PCRE::INFO_CAPTURECOUNT #=> 2
lib U
# In C:
#
# union IntOrFloat {
# int some_int;
# double some_float;
# };
union IntOrFloat
some_int : Int32
some_float : Float64
end
end
value = U::IntOrFloat.new
value = uninitialized U::IntOrFlaot
value.some_int #=> some garbage value
value = U::IntOrFloat.new
value.some_int = 1
value.some_int #=> 1
value.some_float #=> 4.94066e-324
def change_it(value)
value.some_int = 1
end
value = U::IntOrFloat.new
change_it value
value.some_int #=> 0
lib C
# In C:
#
# struct TimeZone {
# int minutes_west;
# int dst_time;
# };
struct TimeZone
minutes_west : Int32
dst_time : Int32
end
end
lib C
# This is a forward declaration
struct Node
end
struct Node
node : Node*
end
end
tz = C::TimeZone.new
tz = uninitialized C::TimeZone
tz.minutes_west #=> some garbage value
tz = C::TimeZone.new
tz.minutes_west = 1
tz.minutes_west #=> 1
tz = C::TimeZone.new minutes_west: 1, dst_time: 2
tz.minutes_west #=> 1
tz.dst_time #=> 2
def change_it(tz)
tz.minutes_west = 1
end
tz = C::TimeZone.new
change_it tz
tz.minutes_west #=> 0
lib C
$errno : Int32
end
C.errno #=> some value
C.errno = 0
C.errno #=> 0
lib C
@[ThreadLocal]
$errno : Int32
end
lib C
fun waitpid(pid : Int32, status_ptr : Int32*, options : Int32) : Int32
end
status_ptr = uninitialized Int32
C.waitpid(pid, pointerof(status_ptr), options)
C.waitpid(pid, out status_ptr, options)
lib X
type CInt = Int32
end
ifdef x86_64
# some specific code for 64 bits platforms
else
# some specific code for non-64 bits platforms
end
ifdef linux && x86_64
# some specific code for linux 64 bits
end
lib C
ifdef linux
struct SomeStruct
some_field : Int32
end
else
struct SomeStruct
some_field : Int64
end
end
end
# Assigns to a local variable
local = 1
# Assigns to a global variable
$global = 4
class Testing
# Assigns to an instance variable
@instance = 2
# Assigns to a class variable
@@class = 3
end
local += 1 # same as: local = local + 1
# The above is valid with these operators:
# +, -, *, /, %, |, &, ^, **, <<, >>
local ||= 1 # same as: local || (local = 1)
local &&= 1 # same as: local && (local = 1)
# A setter
person.name=("John")
# The above can be written as:
person.name = "John"
# An indexed assignment
objects.[]=(2, 3)
# The above can be written as:
objects[2] = 3
# Not assignment-related, but also syntax sugar:
objects.[](2, 3)
# The above can be written as:
objects[2, 3]
person.age += 1 # same as: person.age = person.age + 1
person.name ||= "John" # same as: person.name || (person.name = "John")
person.name &&= "John" # same as: person.name && (person.name = "John")
objects[1] += 2 # same as: objects[1] = objects[1] + 2
objects[1] ||= 2 # same as: objects[1]? || (objects[1] = 2)
objects[1] &&= 2 # same as: objects[1]? && (objects[1] = 2)
alias PInt32 = Pointer(Int32)
ptr = PInt32.malloc(1) # : Pointer(Int32)
alias RecArray = Array(Int32) | Array(RecArray)
ary = [] of RecArray
ary.push [1, 2, 3]
ary.push ary
ary #=> [[1, 2, 3], [...]]
module Json
alias Type = Nil |
Bool |
Int64 |
Float64 |
String |
Array(Type) |
Hash(String, Type)
end
a = 1
if a > 0
a = 10
end
a #=> 10
b = 1
if b > 2
b = 10
else
b = 20
end
b #=> 20
if some_condition
do_something
elsif some_other_condition
do_something_else
else
do_that
end
a = 1
if some_condition
a = "hello"
else
a = true
end
# a : String | Bool
b = 1
if some_condition
b = "hello"
end
# b : Int32 | String
if some_condition
c = 1
else
c = "hello"
end
# c : Int32 | String
if some_condition
d = 1
end
# d : Int32 | Nil
a = 1
if some_condition
a = "hello"
# a : String
a.size
end
# a : String | Int32
if some_condition
e = 1
else
e = "hello"
# e : String
return
end
# e : Int32
enum Color : UInt8
Red # 0
Green # 1
Blue = 5 # overwritten to 5
Yellow # 6 (5 + 1)
def red?
self == Color::Red
end
end
Color::Red.value #:: UInt8
@[Flags]
enum IOMode
Read # 1
Write # 2
Async # 4
end
IOMode::None.value #=> 0
IOMode::All.value #=> 7
puts(Color::Red) # prints "Red"
puts(IOMode::Write | IOMode::Async) # prints "Write, Async"
puts Color.new(1) #=> prints "Green"
puts Color.new(10) #=> prints "10"
Color::Red.red? #=> true
Color::Blue.red? #=> false
def paint(color : Color)
case color
when Color::Red
# ...
else
# Unusual, but still can happen
raise "unknown color: #{color}"
end
end
paint Color::Red
def paint(color : Symbol)
case color
when :red
# ...
else
raise "unknown color: #{color}"
end
end
paint :red
name = "Crystal"
age = 1
flower = "Tulip"
# At this point 'flower' is a String
flower = 1
# At this point 'flower' is an Int32
class Foo
def finalize
# Invoked when Foo is garbage-collected
puts "Bye bye from #{self}!"
end
end
# Prints "Bye bye ...!" for ever
loop do
Foo.new
end
# Defines a method in the program
def add(x, y)
x + y
end
# Invokes the add method in the program
add(1, 2) #=> 3
def even?(num)
if num % 2 == 0
return true
end
return false
end
def add(x, y)
x + y
end
class Foo
def bar
# invokes the program's add method
add(1, 2)
# invokes Foo's baz method
baz(1, 2)
end
def baz(x, y)
x * y
end
end
def baz(x, y)
x + y
end
class Foo
def bar
baz(4, 2) #=> 2
::baz(4, 2) #=> 6
end
def baz(x, y)
x - y
end
end
x = 1
def add(y)
x + y # error: undefined local variable or method 'x'
end
add(2)
add 1, 2 # same as add(1, 2)
class Counter
@@instances = 0
def initialize
@@instances += 1
end
def self.instances
@@instances
end
end
Counter.instances #=> 0
Counter.new
Counter.new
Counter.new
Counter.instances #=> 3
class Counter
def self.increment
@@instances += 1
end
end
Counter.increment # Error: undefined method '+' for Nil
class Parent
@@counter = 0
end
class Child < Parent
def self.counter
@@counter
end
end
Child.counter #=> nil
unless some_condition
then_expression
else
else_expression
end
# Can also be written as a suffix
close_door unless door_closed?
a = 1
b = typeof(a) #=> Int32
typeof(1, "a", 'a') #=> (Int32 | String | Char)
hash = {} of Int32 => String
another_hash = typeof(hash).new #:: Hash(Int32, String)
class Array
def self.elem_type(typ)
if typ.is_a?(Array)
elem_type(typ.first)
else
typ
end
end
end
nest = [1, ["b", [:c, ['d']]]]
flat = Array(typeof(Array.elem_type(nest))).new
typeof(nest) #=> Array(Int32 | Array(String | Array(Symbol | Array(Char))))
typeof(flat) #=> Array(String | Int32 | Symbol | Char)
a = 2 if some_condition
x = 0
proc = ->{ x += 1; x }
proc.call #=> 1
proc.call #=> 2
x #=> 2
def counter
x = 0
->{ x += 1; x }
end
proc = counter
proc.call #=> 1
proc.call #=> 2
def foo
yield
end
x = 1
foo do
x = "hello"
end
x # : Int32 | String
x = 1
foo do
x = "hello"
end
x # : Int32 | String
x = 'a'
x # : Char
def capture(&block)
block
end
x = 1
capture { x = "hello" }
x = 'a'
x # : Int32 | String | Char
def capture(&block)
block
end
x = 1
->{ x = "hello" }
x = 'a'
x # : Int32 | String | Char
abstract class Animal
# Makes this animal talk
abstract def talk
end
class Dog < Animal
def talk
"Woof!"
end
end
class Cat < Animal
def talk
"Miau"
end
end
class Person
getter pet
def initialize(@name, @pet)
end
end
john = Person.new "John", Dog.new
peter = Person.new "Peter", Cat.new
john.pet.talk #=> "Woof!"
a = 1 > 2 ? 3 : 4
# The above is the same as:
a = if 1 > 2
3
else
4
end
def some_method : String
"hello"
end
PI = 3.14
module Earth
RADIUS = 6_371_000
end
PI #=> 3.14
Earth::RADIUS #=> 6_371_000
TEN = begin
a = 0
while a < 10
a += 1
end
a
end
TEN #=> 10
class Person
getter name
def initialize(@name)
@age = 0
end
end
john = Person.new "John"
john.name #=> "John"
john.name.size #=> 4
one = Person.new 1
one.name #=> 1
one.name + 2 #=> 3
john = Person.new "John"
one = Person.new 1
john = Person.new "John"
one = Person.new 1
# Error: undefined method 'size' for Int32
john.name.size
# Error: no overload matches 'String#+' with types Int32
john.name + 3
john = Person.new "John"
john.name.size
one = Person.new 1
class Person
getter name
def initialize(@name)
@age = 0
end
def address
@address
end
def address=(@address)
end
end
john = Person.new "John"
john.address = "Argentina"
# Error: undefined method 'size' for Nil
john.address.size
class Person
@age = 0
def initialize(@name)
end
end
class Person
@age : Int32
def initialize(@name)
@age = 0
end
end
a = if 2 > 1
3
else
4
end
a #=> 3
if 1 > 2
else
3
end
def twice(&block)
yield
yield
end
twice() do
puts "Hello!"
end
twice do
puts "Hello!"
end
twice { puts "Hello!" }
def twice
yield 1
yield 2
end
twice do |i|
puts "Got #{i}"
end
twice { |i| puts "Got #{i}" }
def many
yield 1, 2, 3
end
many do |x, y, z|
puts x + y + z
end
# Output: 6
def many
yield 1, 2, 3
end
many do |x, y|
puts x + y
end
# Output: 3
def twice
yield
yield
end
twice do |i|
puts i.inspect
end
def some
yield 1, 'a'
yield true, "hello"
yield 2
end
some do |first, second|
# first is Int32 | Bool
# second is Char | String | Nil
end
method do |argument|
argument.some_method
end
method(&.some_method)
method &.some_method(arg1, arg2)
method &.+(2)
method &.[index]
def twice
v1 = yield 1
puts v1
v2 = yield 2
puts v2
end
twice do |i|
i + 1
end
ary = [1, 2, 3]
ary.map { |x| x + 1 } #=> [2, 3, 4]
ary.select { |x| x % 2 == 1 } #=> [1, 3]
def transform(value)
yield value
end
transform(1) { |x| x + 1 } #=> 2
def thrice
puts "Before 1"
yield 1
puts "Before 2"
yield 2
puts "Before 3"
yield 3
puts "After 3"
end
thrice do |i|
if i == 2
break
end
end
def twice
yield 1
yield 2
end
twice { |i| i + 1 } #=> 3
twice { |i| break "hello" } #=> "hello"
value = twice do |i|
if i == 1
break "hello"
end
i + 1
end
value #:: Int32 | String
values = twice { break 1, 2 }
values #=> {1, 2}
value = twice { break }
value #=> nil
def twice
yield 1
yield 2
end
twice do |i|
if i == 1
puts "Skipping 1"
next
end
puts "Got #{i}"
end
def twice
v1 = yield 1
puts v1
v2 = yield 2
puts v2
end
twice do |i|
if i == 1
next 10
end
i + 1
end
# Output
# 10
# 3
class Foo
def one
1
end
def yield_with_self
with self yield
end
def yield_normally
yield
end
end
def one
"one"
end
Foo.new.yield_with_self { one } # => 1
Foo.new.yield_normally { one } # => "one"
def twice
yield 1
yield 2
end
twice do |i|
puts "Got: #{i}"
end
i = 1
puts "Got: #{i}"
i = 2
puts "Got: #{i}"
3.times do |i|
puts i
end
struct Int
def times
i = 0
while i < self
yield i
i += 1
end
end
end
i = 0
while i < 3
puts i
i += 1
end
class Person
def initialize(@name)
end
def greet
puts "Hi, I'm #{@name}"
end
end
class Employee < Person
end
employee = Employee.new "John"
employee.greet # "Hi, I'm John"
class Person
def initialize(@name)
end
end
class Employee < Person
def initialize(@name, @company_name)
end
end
Employee.new "John", "Acme" # OK
Employee.new "Peter" # Error: wrong number of arguments
# for 'Employee:Class#new' (1 for 2)
class Person
def greet(msg)
puts "Hi, #{msg}"
end
end
class Employee < Person
def greet(msg)
puts "Hello, #{msg}"
end
end
p = Person.new
p.greet "everyone" # "Hi, everyone"
e = Employee.new
e.greet "everyone" # "Hello, everyone"
class Person
def greet(msg)
puts "Hi, #{msg}"
end
end
class Employee < Person
def greet(msg : Int32)
puts "Hi, this is a number: #{msg}"
end
end
e = Employee.new
e.greet "everyone" # "Hi, everyone"
e.greet 1 # "Hi, this is a number: 1"
class Person
def greet(msg)
puts "Hello, "#{msg}"
end
end
class Employee < Person
def greet(msg)
super # Same as: super(msg)
super("another message")
end
end
def int_to_int(&block : Int32 -> Int32)
block
end
proc = int_to_int { |x| x + 1 }
proc.call(1) #=> 2
class Model
def on_save(&block)
@on_save_callback = block
end
def save
if callback = @on_save_callback
callback.call
end
end
end
model = Model.new
model.on_save { puts "Saved!" }
model.save # prints "Saved!"
def some_proc(&block : Int32 ->)
block
end
proc = some_proc { |x| x + 1 }
proc.call(1) # void
def some_proc(&block : Int32 -> _)
block
end
proc = some_proc { |x| x + 1 }
proc.call(1) # 2
proc = some_proc { |x| x.to_s }
proc.call(1) # "1"
macro update_x
x = 1
end
x = 0
update_x
x #=> 1
macro dont_update_x
%x = 1
puts %x
end
x = 0
dont_update_x # outputs 1
x #=> 0
macro fresh_vars_sample(*names)
# First declare vars
{% for name, index in names %}
print "Declaring: ", "%name{index}", '\n'
%name{index} = {{index}}
{% end %}
# Then print them
{% for name, index in names %}
print "%name{index}: ", %name{index}, '\n'
{% end %}
end
fresh_vars_sample a, b, c
# Sample output:
# Declaring: __temp_255
# Declaring: __temp_256
# Declaring: __temp_257
# __temp_255: 0
# __temp_256: 1
# __temp_257: 2
class Object
macro def instance_vars_names : Array(String)
{{ @type.instance_vars.map &.name.stringify }}
end
end
class Person
def initialize(@name, @age)
end
end
person = Person.new "John", 30
person.instance_vars_names #=> ["name", "age"]
class Object
macro def has_instance_var?(name) : Bool
# We cannot access name inside the macro expansion here,
# instead we need to use the macro language to construct an array
# and do the inclusion check at runtime.
{{ @type.instance_vars.map &.name.stringify }}.includes? name
end
end
person = Person.new "John", 30
person.has_instance_var?("name") #=> true
person.has_instance_var?("birthday") #=> false
class Parent
macro inherited
def {{@type.name.downcase.id}}
1
end
end
end
class Child < Parent
end
Child.new.child #=> 1
macro method_missing(name, args, block)
print "Got ", {{name.id.stringify}}, " with ", {{args.size}}, " arguments", '\n'
end
foo # Prints: Got foo with 0 arguments
bar 'a', 'b' # Prints: Got bar with 2 arguments
sizeof(Int32) #=> 4
sizeof(Int64) #=> 8
# On a 64 bits machine
sizeof(Pointer(Int32)) #=> 8
sizeof(String) #=> 8
a = 1
sizeof(typeof(a)) #=> 4
class Foo
macro emphasize(value)
"***#{ {{value}} }***"
end
def yield_with_self
with self yield
end
end
Foo.new.yield_with_self { emphasize(10) } #=> "***10***"
# This generates:
#
# def :foo
# 1
# end
define_method :foo, 1
macro define_method(name, content)
def {{name.id}}
{{content}}
end
end
# This correctly generates:
#
# def foo
# 1
# end
define_method :foo, 1
macro define_method(name, content)
def {{name}}
{% if content == 1 %}
"one"
{% else %}
{{content}}
{% end %}
end
end
define_method foo, 1
define_method bar, 2
foo #=> one
bar #=> 2
{% if env("TEST") %}
puts "We are in test mode"
{% end %}
macro define_dummy_methods(names)
{% for name, index in names %}
def {{name.id}}
{{index}}
end
{% end %}
end
define_dummy_methods [foo, bar, baz]
foo #=> 0
bar #=> 1
baz #=> 2
macro define_dummy_methods(hash)
{% for key, value in hash %}
def {{key.id}}
{{value}}
end
{% end %}
end
define_dummy_methods({foo: 10, bar: 20})
foo #=> 10
bar #=> 20
{% for name, index in ["foo", "bar", "baz"] %}
def {{name.id}}
{{index}}
end
{% end %}
foo #=> 0
bar #=> 1
baz #=> 2
macro define_dummy_methods(*names)
{% for name, index in names %}
def {{name.id}}
{{index}}
end
{% end %}
end
define_dummy_methods foo, bar, baz
foo #=> 0
bar #=> 1
baz #=> 2
macro println(*values)
print {{*values}}, '\n'
end
println 1, 2, 3 # outputs 123\n
VALUES = [1, 2, 3]
{% for value in VALUES %}
puts {{value}}
{% end %}
until some_condition
do_this
end
# The above is the same as:
while !some_condition
do_this
end
a = some_condition ? nil : 3
# a is Int32 or Nil
if a
# Since the only way to get here is if a is truthy,
# a can't be nil. So here a is Int32.
a.abs
end
if a = some_expression
# here a is not nil
end
if a && b
# here both a and b are guaranteed not to be Nil
end
if @a
# here @a can be nil
end
# First option: assign it to a variable
if a = @a
# here a can't be nil
end
# Second option: use `Object#try` found in the standard library
@a.try do |a|
# here a can't be nil
end
if method # first call to a method that can return Int32 or Nil
# here we know that the first call did not return Nil
method # second call can still return Int32 or Nil
end
class Person
def become_older(by = 1)
@age += by
end
end
john = Person.new "John"
john.age #=> 0
john.become_older
john.age #=> 1
john.become_older 2
john.age #=> 3
john.become_older by: 5
def some_method(x, y = 1, z = 2, w = 3)
# do something...
end
some_method 10 # x = 10, y = 1, z = 2, w = 3
some_method 10, z: 10 # x = 10, y = 1, z = 10, w = 3
some_method 10, w: 1, y: 2, z: 3 # x = 10, y = 2, z = 3, w = 1
case exp
when value1, value2
do_something
when value3
do_something_else
else
do_another_thing
end
case var
when String
# var : String
do_something
when Int32
# var : Int32
do_something_else
else
# here var is neither a String nor an Int32
do_another_thing
end
case num
when .even?
do_something
when .odd?
do_something_else
end
case
when cond1, cond2
do_something
when cond3
do_something_else
end
a = 1
a.responds_to?(:abs) #=> true
a.responds_to?(:size) #=> false
foo_or_bar = /foo|bar/
heeello = /h(e+)llo/
integer = /\d+/
r = /foo/imx
slash = /\//
r = %r(regex with slash: /)
"hello world"
"\"" # double quote
"\\" # backslash
"\e" # escape
"\f" # form feed
"\n" # newline
"\r" # carriage return
"\t" # tab
"\v" # vertical tab
"\101" # == "A"
"\123" # == "S"
"\12" # == "\n"
"\1" # string with one character with code point 1
"\u0041" # == "A"
"\u{41}" # == "A"
"\u{1F52E}" # == "🔮"
"hello
world" # same as "hello\n world"
"hello " \
"world, " \
"no newlines" # same as "hello world, no newlines"
"hello \
world, \
no newlines" # same as "hello world, no newlines"
# Supports double quotes and nested parenthesis
%(hello ("world")) # same as "hello (\"world\")"
# Supports double quotes and nested brackets
%[hello ["world"]] # same as "hello [\"world\"]"
# Supports double quotes and nested curlies
%{hello {"world"}} # same as "hello {\"world\"}"
# Supports double quotes and nested angles
%<hello <"world">> # same as "hello <\"world\">"
<<-XML
<parent>
<child />
</parent>
XML
# Same as "Hello\n world"
<<-STRING
Hello
world
STRING
# Same as " Hello\n world"
<<-STRING
Hello
world
STRING
a = 1
b = 2
"sum = #{a + b}" # "sum = 3"
1.0 # Float64
1.0_f32 # Float32
1_f32 # Float32
1e10 # Float64
1.5e10 # Float64
1.5e-7 # Float64
+1.3 # Float64
-0.5 # Float64
1_000_000.111_111 # better than 1000000.111111
'a'
'z'
'0'
'_'
'あ'
'\'' # single quote
'\\' # backslash
'\e' # escape
'\f' # form feed
'\n' # newline
'\r' # carriage return
'\t' # tab
'\v' # vertical tab
'\101' # == 'A'
'\123' # == 'S'
'\12' # == '\n'
'\1' # code point 1
'\u0041' # == 'A'
'\u{41}' # == 'A'
'\u{1F52E}' # == '🔮'
{1 => 2, 3 => 4} # Hash(Int32, Int32)
{1 => 2, 'a' => 3} # Hash(Int32 | Char, Int32)
{} of Int32 => Int32 # same as Hash(Int32, Int32).new
{key1: 'a', key2: 'b'} # Hash(Symbol, Char)
{"key1": 'a', "key2": 'b'} # Hash(String, Char)
MyType{"foo": "bar"}
tmp = MyType.new
tmp["foo"] = "bar"
tmp
tmp = MyType(typeof("foo"), typeof("bar")).new
tmp["foo"] = "bar"
tmp
MyType(String, String) {"foo": "bar"}
:hello
:good_bye
# With spaces and symbols
:"symbol with spaces"
# Ending with question and exclamation marks
:question?
:exclamation!
# For the operators
:+
:-
:*
:/
:==
:<
:<=
:>
:>=
:!
:!=
:=~
:!~
:&
:|
:^
:~
:**
:>>
:<<
:%
:[]
:[]?
:[]=
:<=>
:===
x..y # an inclusive range, in mathematics: [x, y]
x...y # an exclusive range, in mathematics: [x, y)
# A proc without arguments
->{ 1 } # Proc(Int32)
# A proc with one argument
->(x : Int32) { x.to_s } # Proc(Int32, String)
# A proc with two arguments:
->(x : Int32, y : Int32) { x + y } # Proc(Int32, Int32, Int32)
Proc(Int32, String).new { |x| x.to_s } # Proc(Int32, String)
proc = ->(x : Int32, y : Int32) { x + y }
proc.call(1, 2) #=> 3
def one
1
end
proc = ->one
proc.call #=> 1
def plus_one(x)
x + 1
end
proc = ->plus_one(Int32)
proc.call(41) #=> 42
str = "hello"
proc = ->str.count(Char)
proc.call('e') #=> 1
proc.call('l') #=> 2
tuple = {1, "hello", 'x'} # Tuple(Int32, String, Char)
tuple[0] #=> 1 (Int32)
tuple[1] #=> "hello" (String)
tuple[2] #=> 'x' (Char)
[1, 2, 3] # Array(Int32)
[1, "hello", 'x'] # Array(Int32 | String | Char)
[] of Int32 # same as Array(Int32).new
%w(one two three) # ["one", "two", "three"]
%i(one two three) # [:one, :two, :three]
MyType{1, 2, 3}
tmp = MyType.new
tmp << 1
tmp << 2
tmp << 3
tmp
tmp = MyType(typeof(1, 2, 3)).new
tmp << 1
tmp << 2
tmp << 3
tmp
MyType(Int32 | String) {1, 2, "foo"}
nil
1 # Int32
1_i8 # Int8
1_i16 # Int16
1_i32 # Int32
1_i64 # Int64
1_u8 # UInt8
1_u16 # UInt16
1_u32 # UInt32
1_u64 # UInt64
+10 # Int32
-20 # Int32
2147483648 # Int64
9223372036854775808 # UInt64
1_000_000 # better than 1000000
0b1101 # == 13
0o123 # == 83
0xFE012D # == 16646445
0xfe012d # == 16646445
true # A Bool that is true
false # A Bool that is false
a = 1
ptr = pointerof(a)
ptr.value = 2
a #=> 2
class Point
def initialize(@x, @y)
end
def x
@x
end
def x_ptr
pointerof(@x)
end
end
point = Point.new 1, 2
ptr = point.x_ptr
ptr.value = 10
point.x #=> 10
def add(x : Number, y : Number)
x + y
end
# Ok
add 1, 2 # Ok
# Error: no overload matches 'add' with types Bool, Bool
add true, false
def add(x, y)
x + y
end
add true, false
# A class that has a + method but isn't a Number
class Six
def +(other)
6 + other
end
end
# add method without type restrictions
def add(x, y)
x + y
end
# OK
add Six.new, 10
# add method with type restrictions
def restricted_add(x : Number, y : Number)
x + y
end
# Error: no overload matches 'restricted_add' with types Six, Int32
restricted_add Six.new, 10
class Person
def ==(other : self)
other.name == name
end
def ==(other)
false
end
end
john = Person.new "John"
another_john = Person.new "John"
peter = Person.new "Peter"
john == another_john #=> true
john == peter #=> false (names differ)
john == 1 #=> false (because 1 is not a Person)
class Person
def self.compare(p1 : self, p2 : self)
p1.name == p2.name
end
end
john = Person.new "John"
peter = Person.new "Peter"
Person.compare(john, peter) # OK
def foo(x : Int32)
end
foo 1 # OK
foo "hello" # Error
def foo(x : Int32.class)
end
foo Int32 # OK
foo String # Error
def foo(x : Int32.class)
puts "Got Int32"
end
def foo(x : String.class)
puts "Got String"
end
foo Int32 # prints "Got Int32"
foo String # prints "Got String"
def foo(*args : Int32)
end
def foo(*args : String)
end
foo 1, 2, 3 # OK, invokes first overload
foo "a", "b", "c" # OK, invokes second overload
foo 1, 2, "hello" # Error
foo() # Error
def foo
# This is the empty-tuple case
end
def foo(x : T)
T
end
foo(1) #=> Int32
foo("hello") #=> String
def foo(x : Array(T))
T
end
foo([1, 2]) #=> Int32
foo([1, "a"]) #=> (Int32 | String)
def foo(x : T.class)
Array(T)
end
foo(Int32) #=> Array(Int32)
foo(String) #=> Array(String)
class Person
# Increases age by one
def become_older
@age += 1
end
# Increases age by the given number of years
def become_older(years : Int32)
@age += years
end
# Increases age by the given number of years, as a String
def become_older(years : String)
@age += years.to_i
end
# Yields the current age of this person and increases
# its age by the value returned by the block
def become_older
@age += yield @age
end
end
person = Person.new "John"
person.become_older
person.age #=> 1
person.become_older 5
person.age #=> 6
person.become_older "12"
person.age #=> 18
person.become_older do |current_age|
current_age < 20 ? 10 : 30
end
person.age #=> 28
a = 1
a.is_a?(Int32) #=> true
a.is_a?(String) #=> false
a.is_a?(Number) #=> true
a.is_a?(Int32 | String) #=> true
# One for each thread
@[ThreadLocal]
$values = [] of Int32
@[AlwaysInline]
def foo
1
end
@[NoInline]
def foo
1
end
lib LibFoo
@[CallConvention("X86_StdCall")]
fun foo : Int32
end
def sum(*elements)
total = 0
elements.each do |value|
total += value
end
total
end
# elements is Tuple(Int32, Int32, Int32, Float64)
sum 1, 2, 3, 4.5
if a.responds_to?(:abs)
# here a's type will be reduced to those responding to the 'abs' method
end
a = some_condition ? 1 : "hello"
# a : Int32 | String
if a.responds_to?(:abs)
# here a will be Int32, since Int32#abs exists but String#abs doesn't
else
# here a will be String
end
if (a = @a).responds_to?(:abs)
# here a is guaranteed to respond to `abs`
end
def capture(&block)
block
end
def invoke(&block)
block.call
end
proc = capture { puts "Hello" }
invoke(&proc) # prints "Hello"
def capture(&block)
block
end
def twice
yield
yield
end
proc = capture { puts "Hello" }
twice &proc
twice &->{ puts "Hello" }
def say_hello
puts "Hello"
end
twice &->say_hello
def foo
yield 1
end
def wrap_foo
puts "Before foo"
foo do |x|
yield x
end
puts "After foo"
end
wrap_foo do |i|
puts i
end
def foo
yield 1
end
def wrap_foo(&block : Int32 -> _)
puts "Before foo"
foo(&block)
puts "After foo"
end
wrap_foo do |i|
puts i
end
foo_forward do |i|
break # error
end
a = 2
while (a += 1) < 20
if a == 10
# goes to 'puts a'
break
end
end
puts a #=> 10
class Person
private def say(message)
puts message
end
def say_hello
say "hello" # OK, no receiver
self.say "hello" # Error, self is a receiver
other = Person.new "Other"
other.say "hello" # Error, other is a receiver
end
end
class Employee < Person
def say_bye
say "bye" # OK
end
end
module Namespace
class Foo
protected def foo
puts "Hello"
end
end
class Bar
def bar
# Works, because Foo and Bar are under Namespace
Foo.new.foo
end
end
end
Namespace::Bar.new.bar
class Person
protected def self.say(message)
puts message
end
def say_hello
Person.say "hello"
end
end
buffer = uninitialized UInt8[256]
|