Skip to content

Instantly share code, notes, and snippets.

@wmoxam
Last active October 11, 2016 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmoxam/8a3b34f33dcf6dec7f58100c173389ec to your computer and use it in GitHub Desktop.
Save wmoxam/8a3b34f33dcf6dec7f58100c173389ec to your computer and use it in GitHub Desktop.
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.
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
@ray-delossantos
Copy link

https://play.crystal-lang.org/#/r/1bs6

class  Any(T)
  getter raw : T

  def initialize(@raw : T)
  end

  def foo
    if (raw = @raw).responds_to?(:each)
      raw.each do |e|
        yield e
      end
    end
  end
end

Any.new([1,2,3]).foo {|x| puts x}
Any.new("str").foo {|x| puts x}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment