0x4a6f4672
0x4a6f4672

Reputation: 28245

undefined local variable or method ` ' for main:Object

Sometimes, the following causes a strange bug:

> nil || 4
NameError: undefined local variable or method ` 4' for main:Object

> nil || []
NameError: undefined local variable or method ` ' for main:Object

What is the reason?

Upvotes: 15

Views: 24166

Answers (3)

de.
de.

Reputation: 8507

I had this error when I copied some unsupported quote characters from somewhere.

# does not work
$: << File.join(File.dirname(__FILE__), ‘..’, ‘lib’)

# works (note ‘’ vs '')
$: << File.join(File.dirname(__FILE__), '..', 'lib')

Upvotes: 0

Sindhu Shree
Sindhu Shree

Reputation: 156

I, for one, got a pretty annoying version of this error from a code file that someone else had written. It kept complaining about an undefined space on a line but there was nothing on it. You could place your cursor on the line and it'd only land on the first place a character could go on. Also, no characters(not even space) highlighted on the line after changing editor preferences. Couldn't grep for it either with option-space on a mac.

Finally resolved by reformatting code from the IDE options. It magically introduced extra new lines in the places ruby was complaining about. Just deleted those and voila, no more errors.

Upvotes: 2

Patrick Oscity
Patrick Oscity

Reputation: 54684

You are accidentally typing Alt + Space on your Mac, which produces a non-breaking space. Ruby does not consider this as whitespace, but as part of a variable name. It then complains that the variable does not exist.

Some people like to remap Alt + Space to Space in order to prevent this typo.

I personally like to highlight invisible characters in my text editor, so I notice the typo immediately.

Upvotes: 17

Related Questions