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, #backtrace_locations, #cause, #exception, exception, #inspect, #message, #set_backtrace, #to_s

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.



1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
# File 'error.c', line 1124

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

    name = (argc > 1) ? argv[--argc] : Qnil;
    rb_call_super(argc, argv);
    rb_ivar_set(self, id_name, name);
    {
	rb_thread_t *th = GET_THREAD();
	rb_control_frame_t *cfp =
	    rb_vm_get_ruby_level_next_cfp(th, RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp));
	if (cfp) iseqw = rb_iseqw_new(cfp->iseq);
    }
    rb_ivar_set(self, id_iseq, iseqw);
    return self;
}

Instance Method Details

#local_variablesArray

Return a list of the local variable names defined where this NameError exception was raised.

Internal use only.

Returns:



1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'error.c', line 1166

static VALUE
name_err_local_variables(VALUE self)
{
    VALUE vars = rb_attr_get(self, id_local_variables);

    if (NIL_P(vars)) {
	VALUE iseqw = rb_attr_get(self, id_iseq);
	if (!NIL_P(iseqw)) vars = rb_iseqw_local_variables(iseqw);
	if (NIL_P(vars)) vars = rb_ary_new();
	rb_ivar_set(self, id_local_variables, vars);
    }
    return vars;
}

#nameString?

Return the name associated with this NameError exception.

Returns:



1150
1151
1152
1153
1154
# File 'error.c', line 1150

static VALUE
name_err_name(VALUE self)
{
    return rb_attr_get(self, id_name);
}

#receiverObject

Return the receiver associated with this NameError exception.

Returns:



1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'error.c', line 1352

static VALUE
name_err_receiver(VALUE self)
{
    VALUE *ptr, recv, mesg;

    recv = rb_ivar_lookup(self, id_receiver, Qundef);
    if (recv != Qundef) return recv;

    mesg = rb_attr_get(self, id_mesg);
    if (!rb_typeddata_is_kind_of(mesg, &name_err_mesg_data_type)) {
	rb_raise(rb_eArgError, "no receiver is available");
    }
    ptr = DATA_PTR(mesg);
    return ptr[NAME_ERR_MESG__RECV];
}