Exception: NameError

Inherits:
StandardError show all
Defined in:
error.c,
error.c

Overview

Raised when a given name is invalid or undefined.

puts foo

raises the exception:

NameError: undefined local variable or method `foo' for main:Object

Since constant names must start with a capital:

Fixnum.const_set :answer, 42

raises the exception:

NameError: wrong constant name answer

Direct Known Subclasses

NoMethodError

Defined Under Namespace

Classes: message

Instance Method Summary collapse

Methods inherited from Exception

#==, #backtrace, #exception, exception, #inspect, #message, #set_backtrace

Constructor Details

#new(msg[, name]) ⇒ Object

Construct a new NameError exception. If given the name parameter may subsequently be examined using the NameError.name method.



937
938
939
940
941
942
943
944
945
946
# File 'error.c', line 937

static VALUE
name_err_initialize(int argc, VALUE *argv, VALUE self)
{
    VALUE name;

    name = (argc > 1) ? argv[--argc] : Qnil;
    rb_call_super(argc, argv);
    rb_iv_set(self, "name", name);
    return self;
}

Instance Method Details

#nameString?

Return the name associated with this NameError exception.

Returns:



955
956
957
958
959
# File 'error.c', line 955

static VALUE
name_err_name(VALUE self)
{
    return rb_attr_get(self, rb_intern("name"));
}

#to_sString

Produce a nicely-formatted string representing the NameError.

Returns:



968
969
970
971
972
973
974
975
976
977
# File 'error.c', line 968

static VALUE
name_err_to_s(VALUE exc)
{
    VALUE mesg = rb_attr_get(exc, rb_intern("mesg"));
    VALUE str = mesg;

    if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
    StringValue(str);
    return str;
}