Last active
August 29, 2015 14:18
-
-
Save asterite/85f19248a2db02881f9b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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