Skip to content

Instantly share code, notes, and snippets.

@kmizu
Forked from taku0/duck_and_structural_typing.rb
Last active September 9, 2016 22:22
Show Gist options
  • Save kmizu/421dc04e665b17d58641078d502e5e63 to your computer and use it in GitHub Desktop.
Save kmizu/421dc04e665b17d58641078d502e5e63 to your computer and use it in GitHub Desktop.
# coding: utf-8
def foo(array_or_hash)
if array_or_hash.responds_to?(:values)
# Hashっぽい
array_or_hash.values.join(", ")
else
# きっとArray
array_or_hash.join(", ")
end
end
foo({:a => 1, :b => 2}) #=> "1, 2"
foo([1, 2]) #=> "1, 2"
# Crystalはグローバル解析に基づく型推論 + 条件分岐におけるresponds_to?を特別扱いすることによって
# このようなプログラムを静的に型付けることができている。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment