I am a Ruby beginner. From the book, I know that a Ruby method name should start with a lowercase letter or underscore. But I found different scenarios:
-
If a method is defined outside a class, it can only begin with lowercase letter, Ruby will complain with an error if you try to define a method which begins with an uppercase letter, for example:
define sayHi puts "Hello" end sayHi # => Hellobut, the following code does not work:
define SayHi puts "Hello" end SayHiit will produce an error:
:in `<main>': uninitialized constant SayHi (NameError) -
If a method is defined inside a class, then it can begin with uppercase letter:
class Test def SayHi puts "hello" end end t = Test.new t.SayHi # => hello
Does anyone know why #1 does not work while #2 work? What are the exact rules the ruby method name?
By convention, things that start with uppercase letters are constants. When you invoke
SayHi, you’re telling Ruby to look for a constant with this name. Of course, there isn’t one, so it fails.If you want to invoke the method, you’ll need to add a pair of parentheses. For example,
Inside of a class, the resolution rules are a little different. Let’s define a simple class with a constant and a method named to look like a constant:
Now,
Ais certainly a constant. But what aboutB?So it isn’t a constant, just a method with that name. When we try to access
Bfrom an instance ofC, now Ruby’s looking for a method:If we wanted to access a constant of
Cinstead, we use the scope qualifier:::