class Object
Object
is the default root of all Ruby objects. Object
inherits from BasicObject
which allows creating alternate object hierarchies. Methods on Object
are available to all classes unless explicitly overridden.
Object
mixes in the Kernel
module, making the built-in kernel functions globally accessible. Although the instance methods of Object
are defined by the Kernel
module, we have chosen to document them here for clarity.
When referencing constants in classes inheriting from Object
you do not need to use the full namespace. For example, referencing File
inside YourClass
will find the top-level File
class.
In the descriptions of Object's methods, the parameter symbol refers to a symbol, which is either a quoted string or a Symbol
(such as :name
).
Constants
- ARGF
ARGF
is a stream designed for use in scripts that process files given as command-line arguments or passed in viaSTDIN
.See
ARGF
(the class) for more details.- ARGV
ARGV
contains the command line arguments used to run ruby.A library like
OptionParser
can be used to process command-line arguments.- Bignum
An obsolete class, use
Integer
- CROSS_COMPILING
- DATA
DATA
is aFile
that contains the data section of the executed file. To create a data section use__END__
:$ cat t.rb puts DATA.gets __END__ hello world! $ ruby t.rb hello world!
- ENV
ENV
is a Hash-like accessor for environment variables.See
ENV
(the class) for more details.- Fixnum
An obsolete class, use
Integer
- ParseError
- RUBY_COPYRIGHT
The copyright string for ruby
- RUBY_DESCRIPTION
The full ruby version string, like
ruby -v
prints- RUBY_ENGINE
The engine or interpreter this ruby uses.
- RUBY_ENGINE_VERSION
The version of the engine or interpreter this ruby uses.
- RUBY_PATCHLEVEL
The patchlevel for this ruby. If this is a development build of ruby the patchlevel will be -1
- RUBY_PLATFORM
The platform for this ruby
- RUBY_RELEASE_DATE
The date this ruby was released
- RUBY_REVISION
The GIT commit hash for this ruby.
- RUBY_VERSION
The running version of ruby
- Readline
- STDERR
Holds the original stderr
- STDIN
Holds the original stdin
- STDOUT
Holds the original stdout
- TOPLEVEL_BINDING
The
Binding
of the top level scope- TimeoutError
Raised by
Timeout.timeout
when the block times out.
Public Class Methods
# File ext/psych/lib/psych/core_ext.rb, line 3 def self.yaml_tag url Psych.add_tag(url, self) end
Public Instance Methods
Returns true if two objects do not match (using the =~ method), otherwise false.
static VALUE rb_obj_not_match(VALUE obj1, VALUE obj2) { VALUE result = rb_funcall(obj1, id_match, 1, obj2); return RTEST(result) ? Qfalse : Qtrue; }
Returns 0 if obj
and other
are the same object or obj == other
, otherwise nil.
The #<=> is used by various methods to compare objects, for example Enumerable#sort
, Enumerable#max
etc.
Your implementation of #<=> should return one of the following values: -1, 0, 1 or nil. -1 means self is smaller than other. 0 means self is equal to other. 1 means self is bigger than other. Nil means the two values could not be compared.
When you define #<=>, you can include Comparable
to gain the methods #<=, #<, #==, #>=, #> and between?.
static VALUE rb_obj_cmp(VALUE obj1, VALUE obj2) { if (rb_equal(obj1, obj2)) return INT2FIX(0); return Qnil; }
Case Equality – For class Object
, effectively the same as calling #==
, but typically overridden by descendants to provide meaningful semantics in case
statements.
#define case_equal rb_equal
This method is deprecated.
This is not only useless but also troublesome because it may hide a type error.
static VALUE rb_obj_match(VALUE obj1, VALUE obj2) { if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) { rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "deprecated Object#=~ is called on %"PRIsVALUE "; it always returns nil", rb_obj_class(obj1)); } return Qnil; }
Passes args
to CSV::instance
.
CSV("CSV,data").read #=> [["CSV", "data"]]
If a block is given, the instance is passed the block and the return value becomes the return value of the block.
CSV("CSV,data") { |c| c.read.any? { |a| a.include?("data") } } #=> true CSV("CSV,data") { |c| c.read.any? { |a| a.include?("zombies") } } #=> false
# File lib/csv.rb, line 2653 def CSV(*args, &block) CSV.instance(*args, &block) end
The primary interface to this library. Use to setup delegation when defining your class.
class MyClass < DelegateClass(ClassToDelegateTo) # Step 1 def initialize super(obj_of_ClassToDelegateTo) # Step 2 end end
or:
MyClass = DelegateClass(ClassToDelegateTo) do # Step 1 def initialize super(obj_of_ClassToDelegateTo) # Step 2 end end
Here's a sample of use from Tempfile
which is really a File
object with a few special rules about storage location and when the File
should be deleted. That makes for an almost textbook perfect example of how to use delegation.
class Tempfile < DelegateClass(File) # constant and class member data initialization... def initialize(basename, tmpdir=Dir::tmpdir) # build up file path/name in var tmpname... @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600) # ... super(@tmpfile) # below this point, all methods of File are supported... end # ... end
# File lib/delegate.rb, line 394 def DelegateClass(superclass, &block) klass = Class.new(Delegator) ignores = [*::Delegator.public_api, :to_s, :inspect, :=~, :!~, :===] protected_instance_methods = superclass.protected_instance_methods protected_instance_methods -= ignores public_instance_methods = superclass.public_instance_methods public_instance_methods -= ignores klass.module_eval do def __getobj__ # :nodoc: unless defined?(@delegate_dc_obj) return yield if block_given? __raise__ ::ArgumentError, "not delegated" end @delegate_dc_obj end def __setobj__(obj) # :nodoc: __raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj) @delegate_dc_obj = obj end protected_instance_methods.each do |method| define_method(method, Delegator.delegating_block(method)) protected method end public_instance_methods.each do |method| define_method(method, Delegator.delegating_block(method)) end end klass.define_singleton_method :public_instance_methods do |all=true| super(all) | superclass.public_instance_methods end klass.define_singleton_method :protected_instance_methods do |all=true| super(all) | superclass.protected_instance_methods end klass.define_singleton_method :instance_methods do |all=true| super(all) | superclass.instance_methods end klass.define_singleton_method :public_instance_method do |name| super(name) rescue NameError raise unless self.public_instance_methods.include?(name) superclass.public_instance_method(name) end klass.define_singleton_method :instance_method do |name| super(name) rescue NameError raise unless self.instance_methods.include?(name) superclass.instance_method(name) end klass.module_eval(&block) if block return klass end
Returns a Digest
subclass by name
in a thread-safe manner even when on-demand loading is involved.
require 'digest' Digest("MD5") # => Digest::MD5 Digest(:SHA256) # => Digest::SHA256 Digest(:Foo) # => LoadError: library not found for class Digest::Foo -- digest/foo
# File ext/digest/lib/digest.rb, line 96 def Digest(name) const = name.to_sym Digest::REQUIRE_MUTEX.synchronize { # Ignore autoload's because it is void when we have #const_missing Digest.const_missing(const) } rescue LoadError # Constants do not necessarily rely on digest/*. if Digest.const_defined?(const) Digest.const_get(const) else raise end end
Defines a singleton method in the receiver. The method parameter can be a Proc
, a Method
or an UnboundMethod
object. If a block is specified, it is used as the method body. If a block or a method has parameters, they're used as method parameters.
class A class << self def class_name to_s end end end A.define_singleton_method(:who_am_i) do "I am: #{class_name}" end A.who_am_i # ==> "I am: A" guy = "Bob" guy.define_singleton_method(:hello) { "#{self}: Hello there!" } guy.hello #=> "Bob: Hello there!" chris = "Chris" chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" } chris.greet("Hi") #=> "Hi, I'm Chris!"
static VALUE rb_obj_define_method(int argc, VALUE *argv, VALUE obj) { VALUE klass = rb_singleton_class(obj); return rb_mod_define_method(argc, argv, klass); }
Prints obj on the given port (default $>
). Equivalent to:
def display(port=$>) port.write self nil end
For example:
1.display "cat".display [ 4, 5, 6 ].display puts
produces:
1cat[4, 5, 6]
static VALUE rb_obj_display(int argc, VALUE *argv, VALUE self) { VALUE out; out = (!rb_check_arity(argc, 0, 1) ? rb_ractor_stdout() : argv[0]); rb_io_write(out, self); return Qnil; }
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference.
This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy
method of the class.
on dup vs clone¶ ↑
In general, clone
and dup
may have different semantics in descendant classes. While clone
is used to duplicate an object, including its internal state, dup
typically uses the class of the descendant object to create the new instance.
When using dup
, any modules that the object has been extended with will not be copied.
class Klass attr_accessor :str end module Foo def foo; 'foo'; end end s1 = Klass.new #=> #<Klass:0x401b3a38> s1.extend(Foo) #=> #<Klass:0x401b3a38> s1.foo #=> "foo" s2 = s1.clone #=> #<Klass:0x401be280> s2.foo #=> "foo" s3 = s1.dup #=> #<Klass:0x401c1084> s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401c1084>
VALUE rb_obj_dup(VALUE obj) { VALUE dup; if (special_object_p(obj)) { return obj; } dup = rb_obj_alloc(rb_obj_class(obj)); init_copy(dup, obj); rb_funcall(dup, id_init_dup, 1, obj); return dup; }
Creates a new Enumerator
which will enumerate by calling method
on obj
, passing args
if any. What was yielded by method becomes values of enumerator.
If a block is given, it will be used to calculate the size of the enumerator without the need to iterate it (see Enumerator#size
).
Examples¶ ↑
str = "xyz" enum = str.enum_for(:each_byte) enum.each { |b| puts b } # => 120 # => 121 # => 122 # protect an array from being modified by some_method a = [1, 2, 3] some_method(a.to_enum) # String#split in block form is more memory-effective: very_large_string.split("|") { |chunk| return chunk if chunk.include?('DATE') } # This could be rewritten more idiomatically with to_enum: very_large_string.to_enum(:split, "|").lazy.grep(/DATE/).first
It is typical to call to_enum
when defining methods for a generic Enumerable
, in case no block is passed.
Here is such an example, with parameter passing and a sizing block:
module Enumerable # a generic method to repeat the values of any enumerable def repeat(n) raise ArgumentError, "#{n} is negative!" if n < 0 unless block_given? return to_enum(__method__, n) do # __method__ is :repeat here sz = size # Call size and multiply by n... sz * n if sz # but return nil if size itself is nil end end each do |*val| n.times { yield *val } end end end %i[hello world].repeat(2) { |w| puts w } # => Prints 'hello', 'hello', 'world', 'world' enum = (1..14).repeat(3) # => returns an Enumerator when called without a block enum.first(4) # => [1, 1, 1, 2] enum.size # => 42
Equality — At the Object
level, #== returns true
only if obj
and other
are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.
Unlike #==, the equal?
method should never be overridden by subclasses as it is used to determine object identity (that is, a.equal?(b)
if and only if a
is the same object as b
):
obj = "a" other = obj.dup obj == other #=> true obj.equal? other #=> false obj.equal? obj #=> true
The eql?
method returns true
if obj
and other
refer to the same hash key. This is used by Hash
to test members for equality. For any pair of objects where eql?
returns true
, the hash
value of both objects must be equal. So any subclass that overrides eql?
should also override hash
appropriately.
For objects of class Object
, eql?
is synonymous with #==. Subclasses normally continue this tradition by aliasing eql?
to their overridden #== method, but there are exceptions. Numeric
types, for example, perform type conversion across #==, but not across eql?
, so:
1 == 1.0 #=> true 1.eql? 1.0 #=> false
MJIT_FUNC_EXPORTED VALUE rb_obj_equal(VALUE obj1, VALUE obj2) { if (obj1 == obj2) return Qtrue; return Qfalse; }
Adds to obj the instance methods from each module given as a parameter.
module Mod def hello "Hello from Mod.\n" end end class Klass def hello "Hello from Klass.\n" end end k = Klass.new k.hello #=> "Hello from Klass.\n" k.extend(Mod) #=> #<Klass:0x401b3bc8> k.hello #=> "Hello from Mod.\n"
static VALUE rb_obj_extend(int argc, VALUE *argv, VALUE obj) { int i; ID id_extend_object, id_extended; CONST_ID(id_extend_object, "extend_object"); CONST_ID(id_extended, "extended"); rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); for (i = 0; i < argc; i++) Check_Type(argv[i], T_MODULE); while (argc--) { rb_funcall(argv[argc], id_extend_object, 1, obj); rb_funcall(argv[argc], id_extended, 1, obj); } return obj; }
Prevents further modifications to obj. A RuntimeError
will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?
.
This method returns self.
a = [ "a", "b", "c" ] a.freeze a << "z"
produces:
prog.rb:3:in `<<': can't modify frozen Array (FrozenError) from prog.rb:3
Objects of the following classes are always frozen: Integer
, Float
, Symbol
.
VALUE rb_obj_freeze(VALUE obj) { if (!OBJ_FROZEN(obj)) { OBJ_FREEZE(obj); if (SPECIAL_CONST_P(obj)) { rb_bug("special consts should be frozen."); } } return obj; }
Generates an Integer
hash value for this object. This function must have the property that a.eql?(b)
implies a.hash == b.hash
.
The hash value is used along with eql?
by the Hash
class to determine if two objects reference the same hash key. Any hash value that exceeds the capacity of an Integer
will be truncated before being used.
The hash value for an object may not be identical across invocations or implementations of Ruby. If you need a stable identifier across Ruby invocations and implementations you will need to generate one with a custom method.
Certain core classes such as Integer
use built-in hash calculations and do not call the hash
method when used as a hash key.
VALUE rb_obj_hash(VALUE obj) { long hnum = any_hash(obj, objid_hash); return ST2FIX(hnum); }
Returns a string containing a human-readable representation of obj. The default inspect
shows the object's class name, an encoding of its memory address, and a list of the instance variables and their values (by calling inspect
on each of them). User defined classes should override this method to provide a better representation of obj. When overriding this method, it should return a string whose encoding is compatible with the default external encoding.
[ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]" Time.new.inspect #=> "2008-03-08 19:43:39 +0900" class Foo end Foo.new.inspect #=> "#<Foo:0x0300c868>" class Bar def initialize @bar = 1 end end Bar.new.inspect #=> "#<Bar:0x0300c868 @bar=1>"
static VALUE rb_obj_inspect(VALUE obj) { if (rb_ivar_count(obj) > 0) { VALUE str; VALUE c = rb_class_name(CLASS_OF(obj)); str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void*)obj); return rb_exec_recursive(inspect_obj, obj, str); } else { return rb_any_to_s(obj); } }
Returns true
if obj is an instance of the given class. See also Object#kind_of?
.
class A; end class B < A; end class C < B; end b = B.new b.instance_of? A #=> false b.instance_of? B #=> true b.instance_of? C #=> false
VALUE rb_obj_is_instance_of(VALUE obj, VALUE c) { c = class_or_module_required(c); if (rb_obj_class(obj) == c) return Qtrue; return Qfalse; }
Returns true
if the given instance variable is defined in obj. String
arguments are converted to symbols.
class Fred def initialize(p1, p2) @a, @b = p1, p2 end end fred = Fred.new('cat', 99) fred.instance_variable_defined?(:@a) #=> true fred.instance_variable_defined?("@b") #=> true fred.instance_variable_defined?("@c") #=> false
static VALUE rb_obj_ivar_defined(VALUE obj, VALUE iv) { ID id = id_for_var(obj, iv, instance); if (!id) { return Qfalse; } return rb_ivar_defined(obj, id); }