instance method
Object#inspect
() -> ::String
obj.inspect → string
object.c
View on GitHub ↗
static VALUE
rb_obj_inspect(VALUE obj)
{
VALUE ivars = rb_check_funcall(obj, id_instance_variables_to_inspect, 0, 0);
st_index_t n = 0;
if (UNDEF_P(ivars) || NIL_P(ivars)) {
n = rb_ivar_count(obj);
ivars = Qnil;
}
else if (RB_TYPE_P(ivars, T_ARRAY)) {
n = RARRAY_LEN(ivars);
}
else {
rb_raise(
rb_eTypeError,
"Expected #instance_variables_to_inspect to return an Array or nil, but it returned %"PRIsVALUE,
rb_obj_class(ivars)
);
}
if (n > 0) {
VALUE c = rb_class_name(CLASS_OF(obj));
VALUE args[2] = {
rb_sprintf("-<%"PRIsVALUE":%p", c, (void*)obj),
ivars
};
return rb_exec_recursive(inspect_obj, obj, (VALUE)args);
}
else {
return rb_any_to_s(obj);
}
}
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.
Example
[ 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>"
If obj responds to instance_variables_to_inspect, then only the instance variables listed in the returned array will be included in the inspect string.
Example
class DatabaseConfig def initialize(host, user, password) @host = host @user = user @password = password end private def instance_variables_to_inspect = [:@host, :@user] end conf = DatabaseConfig.new("localhost", "root", "hunter2") conf.inspect #=> #<DatabaseConfig:0x0000000104def350 @host="localhost", @user="root">
See also
#hash
#instance_of?
#freeze
#instance_variable_defined?
also in
4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0