Skip to content

Instantly share code, notes, and snippets.

@bhensley
Last active August 29, 2015 14:01
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 bhensley/92e7bf731b48d37f5787 to your computer and use it in GitHub Desktop.
Save bhensley/92e7bf731b48d37f5787 to your computer and use it in GitHub Desktop.
Ruby Data Type Checking: Little metaprogramming fun
##
# 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