Ruby Programming/Reference/Built-In Functions

From Wikibooks, open books for an open world
Jump to navigation Jump to search

By default many methods are available. You can see the available ones by running methods in an irb session, ex:

>> class A; end
>> A.instance_methods

[:nil?, :===, :=~, :!~, :eql?, :class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :define_singleton_method, :hash, :__id__, :object_id, :to_enum, :enum_for, :gem, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__]

You can see where most of those methods are defined by inspecting the object hierarchy:

>> A.ancestors
=> [A, Object, Kernel, BasicObject]

1.9 introduced a few more has __method__ (the current method name), as well as require_relative, which requires a file relative to the dir of the current file.

To see where each methods was defined, you can run something like:

>> A.instance_methods.map{|m| [m,  A.instance_method(m).owner] }
=> [[:nil?, Kernel], ...