Sheharyar Naseer

Search Methods of a Ruby Object


Sometimes, I’m not so sure about the methods I can call on an Object in Ruby. Sure, I can call .methods on that object to get a list of all the functions, but it isn’t always helpful because it can fill up your entire terminal with hundreds of methods you don’t want to see. I wanted to be able to get a list of only those methods that match a certain string I provide. So I overrode Ruby’s Object Class with a custom method called search_methods, it does exactly what it says; searches all methods of an object that match a certain criteria.

class Object
	def search_methods(qry)
		self.methods & self.methods.select { |m| m.to_s.include?(qry.to_s) }
	end
end

You can now call it on different objects like this:

Array.search_methods 'enum'
# => [:to_enum, :enum_for]

Player.last.search_methods :trust
# => [:untrust, :untrusted?, :trust]

"hello".search_methods "to_"
# => [:to_i, :to_f, :to_s, :to_str, :to_sym, :to_r, :to_c, :to_enum]

You can see the Gist on Github. I’ve also added it to my .irbrc in my ~/.dotfiles so this always gets preloaded whenever I run irb or rails c. You can see it in the Class Overrides of my .irbrc

Note: Post updated for awesome_print compatibility and symbol support.