Skip to content

Instantly share code, notes, and snippets.

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 futureperfect/066c6c320c9d0930fe648990a86ba4f4 to your computer and use it in GitHub Desktop.
Save futureperfect/066c6c320c9d0930fe648990a86ba4f4 to your computer and use it in GitHub Desktop.
A couple handy idioms for exploring ruby classes/objects and the methods they implement
# What methods does a class implement?
> Time.methods
=> [:!, :!=, :!~, :<, :<=, :<=>, :==, :===, :=~, :>, :>=, :__id__, :__send__, :allocate, :ancestors, :at, :autoload, :autoload?, :class, :class_eval, :class_exec, :class_variable_defined?, :class_variable_get, :class_variable_set, :class_variables, :clone, :const_defined?, :const_get, :const_missing, :const_set, :constants, :define_singleton_method, :deprecate_constant, :display, :dup, :enum_for, :eql?, :equal?, :extend, :freeze, :frozen?, :gm, :hash, :include, :include?, :included_modules, :inspect, :instance_eval, :instance_exec, :instance_method, :instance_methods, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :is_a?, :itself, :kind_of?, :local, :method, :method_defined?, :methods, :mktime, :module_eval, :module_exec, :name, :new, :nil?, :now, :object_id, :prepend, :private_class_method, :private_constant, :private_instance_methods, :private_method_defined?, :private_methods, :protected_instance_methods, :protected_method_defined?, :protected_methods, :public_class_method, :public_constant, :public_instance_method, :public_instance_methods, :public_method, :public_method_defined?, :public_methods, :public_send, :remove_class_variable, :remove_instance_variable, :respond_to?, :send, :singleton_class, :singleton_class?, :singleton_method, :singleton_methods, :superclass, :taint, :tainted?, :tap, :to_enum, :to_s, :trust, :untaint, :untrust, :untrusted?, :utc]
# That's a ton of stuff! Most of it doesn't look to be time-related. Most of it looks like things that we get from `Object`.
# What if we want to see the things that Time implements that don't come from `Object`?
> Time.methods - Object.methods
=> [:at, :now, :utc, :gm, :local, :mktime]
# That's a much more reasonable to read.
# Finally, what if I'm looking for a method that has a name that I *kind of* remember, but I'm not quite sure what it was
> a = [[1, 2, 3]]
=> [[1, 2, 3]]
# Didn't arrays have a thing that let me make them flat (i.e. not nested?)
> a.methods.grep /flat/
=> [:flatten, :flatten!, :flat_map]
# Hmm... `:flatten` looks like the one I was looking for.
> a.flatten
=> [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment