Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.
class Fred attr_accessor :a1 def initialize @iv = 3 end end Fred.new.instance_variables #=> [:@iv]
Similar to method, searches singleton method only.
class Demo def initialize(n) @iv = n end def hello() "Hello, @iv = #{@iv}" end end k = Demo.new(99) def k.hi "Hi, @iv = #{@iv}" end m = k.singleton_method(:hi) m.call #=> "Hi, @iv = 99" m = k.singleton_method(:hello) #=> NameError
Invokes the method identified by symbol, passing it any arguments specified. Unlike send, public_send
calls public methods only. When the method is identified by a string, the string is converted to a symbol.
1.public_send(:puts, "hello") # causes NoMethodError
Returns true
if obj responds to the given method. Private and protected methods are included in the search only if the optional second parameter evaluates to true
.
If the method is not implemented, as Process.fork
on Windows, File.lchmod
on GNU/Linux, etc., false is returned.
If the method is not defined, respond_to_missing?
method is called and the result is returned.
When the method name parameter is given as a string, the string is converted to a symbol.
Sets the backtrace value for self
; returns the given value
.
The value
might be:
an array of Thread::Backtrace::Location
;
an array of String
instances;
a single String
instance; or
nil
.
Using array of Thread::Backtrace::Location
is the most consistent option: it sets both backtrace
and backtrace_locations
. It should be preferred when possible. The suitable array of locations can be obtained from Kernel#caller_locations
, copied from another error, or just set to the adjusted result of the current error’s backtrace_locations
:
require 'json' def parse_payload(text) JSON.parse(text) # test.rb, line 4 rescue JSON::ParserError => ex ex.set_backtrace(ex.backtrace_locations[2...]) raise end parse_payload('{"wrong: "json"') # test.rb:4:in 'Object#parse_payload': unexpected token at '{"wrong: "json"' (JSON::ParserError) # # An error points to the body of parse_payload method, # hiding the parts of the backtrace related to the internals # of the "json" library # The error has both #backtace and #backtrace_locations set # consistently: begin parse_payload('{"wrong: "json"') rescue => ex p ex.backtrace # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"] p ex.backtrace_locations # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"] end
When the desired stack of locations is not available and should be constructed from scratch, an array of strings or a singular string can be used. In this case, only backtrace
is affected:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(["dsl.rb:34", "framework.rb:1"]) # The error have the new value in #backtrace: p ex.backtrace # ["dsl.rb:34", "framework.rb:1"] # but the original one in #backtrace_locations p ex.backtrace_locations # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...] end parse_payload('{"wrong: "json"')
Calling set_backtrace
with nil
clears up backtrace
but doesn’t affect backtrace_locations
:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(nil) p ex.backtrace # nil p ex.backtrace_locations # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...] end parse_payload('{"wrong: "json"')
On reraising of such an exception, both backtrace
and backtrace_locations
is set to the place of reraising:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(nil) raise # test.rb, line 7 end begin parse_payload('{"wrong: "json"') rescue => ex p ex.backtrace # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"] p ex.backtrace_locations # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"] end
See Backtraces.
Methods Exception#as_json
and Exception.json_create
may be used to serialize and deserialize a Exception object; see Marshal
.
Method Exception#as_json
serializes self
, returning a 2-element hash representing self
:
require 'json/add/exception' x = Exception.new('Foo').as_json # => {"json_class"=>"Exception", "m"=>"Foo", "b"=>nil}
Method JSON.create
deserializes such a hash, returning a Exception object:
Exception.json_create(x) # => #<Exception: Foo>
Returns a JSON
string representing self
:
require 'json/add/exception' puts Exception.new('Foo').to_json
Output:
{"json_class":"Exception","m":"Foo","b":null}
Return a list of the local variable names defined where this NameError
exception was raised.
Internal use only.
Returns an array of all modules used in the current scope. The ordering of modules in the resulting array is not defined.
module A refine Object do end end module B refine Object do end end using A using B p Module.used_modules
produces:
[B, A]
Returns an array of all modules used in the current scope. The ordering of modules in the resulting array is not defined.
module A refine Object do end end module B refine Object do end end using A using B p Module.used_refinements
produces:
[#<refinement:Object@B>, #<refinement:Object@A>]
Invoked as a callback whenever a constant is assigned on the receiver
module Chatty def self.const_added(const_name) super puts "Added #{const_name.inspect}" end FOO = 1 end
produces:
Added :FOO
If we define a class using the class
keyword, const_added
runs before inherited
:
module M def self.const_added(const_name) super p :const_added end parent = Class.new do def self.inherited(subclass) super p :inherited end end class Child < parent end end
produces:
:const_added :inherited
Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling “attr
:name” on each name in turn. String
arguments are converted to symbols. Returns an array of defined method names as symbols.
Creates an accessor method to allow assignment to the attribute symbol.id2name
. String
arguments are converted to symbols. Returns an array of defined method names as symbols.
Checks for a constant with the given name in mod. If inherit
is set, the lookup will also search the ancestors (and Object
if mod is a Module
).
The value of the constant is returned if a definition is found, otherwise a NameError
is raised.
Math.const_get(:PI) #=> 3.14159265358979
This method will recursively look up constant names if a namespaced class name is provided. For example:
module Foo; class Bar; end end Object.const_get 'Foo::Bar'
The inherit
flag is respected on each lookup. For example:
module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10 Object.const_get 'Foo::Baz::VAL', false # => NameError
If the argument is not a valid constant name a NameError
will be raised with a warning “wrong constant name”.
Object.const_get 'foobar' #=> NameError: wrong constant name foobar
Says whether mod or its ancestors have a constant with the given name:
Float.const_defined?(:EPSILON) #=> true, found in Float itself Float.const_defined?("String") #=> true, found in Object (ancestor) BasicObject.const_defined?(:Hash) #=> false
If mod is a Module
, additionally Object
and its ancestors are checked:
Math.const_defined?(:String) #=> true, found in Object
In each of the checked classes or modules, if the constant is not present but there is an autoload for it, true
is returned directly without autoloading:
module Admin autoload :User, 'admin/user' end Admin.const_defined?(:User) #=> true
If the constant is not found the callback const_missing
is not called and the method returns false
.
If inherit
is false, the lookup only checks the constants in the receiver:
IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor) IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
In this case, the same logic for autoloading applies.
If the argument is not a valid constant name a NameError
is raised with the message “wrong constant name name”:
Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
Removes the definition of the given constant, returning that constant’s previous value. If that constant referred to a module, this will not change that module’s name and can lead to confusion.
Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for the undefined constant, and returns a value to be used for that constant. For example, consider:
def Foo.const_missing(name) name # return the constant name as Symbol end Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
As the example above shows, const_missing
is not required to create the missing constant in mod, though that is often a side-effect. The caller gets its return value when triggered. If the constant is also defined, further lookups won’t hit const_missing
and will return the value stored in the constant as usual. Otherwise, const_missing
will be invoked again.
In the next example, when a reference is made to an undefined constant, const_missing
attempts to load a file whose path is the lowercase version of the constant name (thus class Fred
is assumed to be in file fred.rb
). If defined as a side-effect of loading the file, the method returns the value stored in the constant. This implements an autoload feature similar to Kernel#autoload
and Module#autoload
, though it differs in important ways.
def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Constant not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file const_get(name, false) end
Returns an array of the names of class variables in mod. This includes the names of class variables in any included modules, unless the inherit parameter is set to false
.
class One @@var1 = 1 end class Two < One @@var2 = 2 end One.class_variables #=> [:@@var1] Two.class_variables #=> [:@@var2, :@@var1] Two.class_variables(false) #=> [:@@var2]
Makes a list of existing constants public.
Makes a list of existing constants private.
Makes a list of existing constants deprecated. Attempt to refer to them will produce a warning.
module HTTP NotFound = Exception.new NOT_FOUND = NotFound # previous version of the library used this name deprecate_constant :NOT_FOUND end HTTP::NOT_FOUND # warning: constant HTTP::NOT_FOUND is deprecated
Returns true
if mod is a singleton class or false
if it is an ordinary class or module.
class C end C.singleton_class? #=> false C.singleton_class.singleton_class? #=> true
Returns true
if the arguments define a valid commercial date, false
otherwise:
Date.valid_commercial?(2001, 5, 6) # => true Date.valid_commercial?(2001, 5, 8) # => false
See Date.commercial
.
See argument start.
Related: Date.jd
, Date.commercial
.
Returns a copy of self
with the given start
value:
d0 = Date.new(2000, 2, 3) d0.julian? # => false d1 = d0.new_start(Date::JULIAN) d1.julian? # => true
See argument start.