Last active
August 29, 2015 14:01
-
-
Save bhensley/92e7bf731b48d37f5787 to your computer and use it in GitHub Desktop.
Ruby Data Type Checking: Little metaprogramming fun
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
## | |
# Provides functionality for checking if given object is of a specific data type. | |
# --- | |
# Currently supporting the following data types: | |
# * Array | |
# * String | |
# * Integer | |
# | |
# = Example | |
# users = ['jack', 'joe', 'john', 'anotherJname'] | |
# puts "This will happen, as it's true" if users.is_array? | |
# | |
# str = "Hello world!" | |
# puts "This too will happen" if str.is_string? | |
# | |
# puts "Oh, and this is going to happen" if 10.is_int? | |
# | |
class Object | |
@@typeConv = { | |
:array => 'Array', | |
:string => 'String', | |
:int => 'Integer' | |
} | |
def method_missing(method, *args, &block) | |
if method.to_s =~ /is_(\w+)\?/ && @@typeConv[$1.to_sym] | |
type = $1.to_sym | |
is = false | |
self.tap do |o| | |
is = o.kind_of?(eval(@@typeConv[type])) | |
end | |
is | |
else | |
super | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment