4 ms·
> Can you magically return/break out of iterator functions like you can in Ruby? Sure can. $ cat break.cr (1..).each do |x| break if x > 2
by bhaney 2y ago
> Can you magically return/break out of iterator functions like you can in Ruby?
Sure can.
$ cat break.cr
(1..).each do |x|
break if x > 2
puts x
end
$ crystal break.cr
1
2
$
The answer to Crystal questions that end in "like you can in Ruby" is usually "yes." The language really is just Ruby with static typing, warts and all. Most random snippets of Ruby will run just fine when compiled as Crystal.
- dangitman 2y ago[dead]
- woodruffw 2y agoI agree this is weird, but I think it's largely an analogy issue: Ruby and Crystal both explicitly document blocks as not being closures, even when they can be converted into closures. They're their own weird thing. Crystal also documents that it will fail if the block contains return or break statements[1]. [1]: https://crystal-lang.org/reference/1.13/syntax_and_semantics/capturing_blocks.html#break-and-next https://crystal-lang.org/reference/1.13/syntax_and_semantics...
- deleted 2y ago[deleted]
- straight-shoota 2y agoI'm a core developer of Crystal. Note that there are two different flavours of blocks in Crystal: inlined and captured ones. `return` and `break` are supported in inlined blocks.