Last active
October 11, 2016 06:34
-
-
Save wmoxam/8a3b34f33dcf6dec7f58100c173389ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Any | |
alias Type = Array(Int32) | String | Nil | |
getter raw : Type | |
def initialize(raw) | |
@raw = raw.as Type | |
end | |
def foo | |
if @raw.responds_to?(:each) | |
@raw.each do |e| | |
yield e | |
end | |
end | |
end | |
end | |
Any.new("a").foo {|x| puts x} | |
Any.new(nil).foo {|x| puts x} | |
Any.new([1,2,3]).foo {|x| puts x} | |
$ crystal test.cr | |
Error in ./test.cr:18: instantiating 'Any#foo()' | |
Any.new("a").foo {|x| puts x} | |
^~~ | |
in ./test.cr:11: undefined method 'each' for String (compile-time type is (Array(Int32) | String | Nil)) | |
@raw.each do |e| | |
^~~~ | |
Rerun with --error-trace to show a complete error trace. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
alias Type = Array(Int32) | String | Nil | |
def foo(r) | |
raw = r.as Type | |
if raw.responds_to?(:each) | |
raw.each do |e| | |
yield e | |
end | |
end | |
end | |
foo("a") {|x| puts x} | |
foo(nil) {|x| puts x} | |
foo([1,2,3]) {|x| puts x} | |
$ crystal test2.cr | |
1 | |
2 | |
3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.crystal-lang.org/#/r/1bs6