Skip to content

Instantly share code, notes, and snippets.

@asterite
Last active August 29, 2015 14:18
Show Gist options
  • Save asterite/85f19248a2db02881f9b to your computer and use it in GitHub Desktop.
Save asterite/85f19248a2db02881f9b to your computer and use it in GitHub Desktop.
struct Block
def initialize(str : String)
@data = str
end
def initialize(int : Int32)
@data = int
end
def data
@data
end
end
# So @data is String | Int32, a union
str_block = Block.new "Hello"
int_block = Block.new 1
p str_block.data #=> "Hello"
p int_block.data #=> 1
# You can't invoke a method on data if it's not on all types
# str_block.data.length #=> undefined method 'length' for Int32
# str_block.data.abs #=> undefined method 'abs' for String
data = str_block.data
case data
when String
puts "Data is a string: #{data}"
when Int32
puts "Data is an int: #{data}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment