Question about RSPEC 4 Capitalization

Hi,

I have a quick question about the difference between lower_words and LOWER_WORDS as a variable name. The code below passes all the tests, but if I replace both instances of “LOWER_WORDS” with “lower_words”, I get the following error:

NameError:
undefined local variable or method `lower_words’ for #Book:0x00007f91d5a4fa10

Could someone explain the issue here?

class Book
LOWER_WORDS = [
“the”,
“a”,
“an”,
“and”,
“in”,
“of”
]

attr_reader :title

def title=(title)
title_words = title.split(" “)
capitalized = title_words.map.with_index do |word, idx|
if LOWER_WORDS.include?(word) && idx != 0
word
else
word.capitalize
end
end
@title = capitalized.join(” ")
end
end

LOWER_WORDS is a Ruby Constant. Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally.
When you change it to “lower_words”, it becomes a local variable and cannot be accessed outside your method.

1 Like