Skip to content

Commit 2f2015d

Browse files
committed
(WIP) Alternative syntaxes
1 parent d15fc14 commit 2f2015d

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

docs/tutorials/basics/70_blocks.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,3 +348,74 @@ transform_string "crystal" do |word|
348348
word.capitalize
349349
end
350350
```
351+
352+
## Alternative syntaxes
353+
354+
We almost at the end of this section. Let's see some other interesting ways of writing _blocks_.
355+
356+
### Curly braces
357+
358+
Another way of defining a _block_ is using `{...}` instead of `do ... end`. Here is one of the examples we have already seen but written with _curly braces syntax_:
359+
360+
```crystal-play
361+
def other_method
362+
yield 42, "Hello", [1, "Crystal", 3]
363+
end
364+
365+
other_method { |n, s, arr|
366+
puts "#{s} #{arr[1]}"
367+
puts n
368+
}
369+
```
370+
371+
Here is the `_` example written with _curly braces syntax_ and in one line:
372+
373+
```crystal-play
374+
def other_method
375+
yield 42, "Hello", [1, "Crystal", 3]
376+
end
377+
378+
other_method { |_, _, arr| puts arr[1] }
379+
```
380+
381+
The main difference between using `do ... end` and `{ ... }` is how they bind the call:
382+
383+
- `do ... end` binds to left-most call
384+
- `{ ... }` binds to the right-most call
385+
386+
```crystal-play
387+
def generate_number()
388+
42
389+
end
390+
391+
def with_double(n : Int32)
392+
yield n * 2
393+
end
394+
395+
with_double generate_number do |n|
396+
puts n
397+
end
398+
399+
# Same as:
400+
with_double(generate_number) do |n|
401+
puts n
402+
end
403+
```
404+
405+
But with `curly braces syntax`:
406+
407+
```crystal
408+
def generate_number()
409+
42
410+
end
411+
412+
def with_double(n : Int32)
413+
yield n * 2
414+
end
415+
416+
with_double generate_number { |n| puts n } # Error: 'generate_number' is not expected to be invoked with a block, but a block was given
417+
```
418+
419+
The error is because with _curly braces_ we are writing: `with_double(generate_number { |n| puts n })` instead of `with_double(generate_number) { |n| puts n }`
420+
421+
### Short one-parameter syntax

0 commit comments

Comments
 (0)