1

The following code is from the book Exceptional Ruby:

starts_with_a = Object.new

def starts_with_a. ===(e)
    /^A/ =~ e.name
end 

If I comment out the first line where a new object is assigned to starts_with_a, then I get this error:

`<main>': undefined local variable or method `starts_with_a' for main:Object (NameError)

Question 1: why do I need to assign a new object to starts_with_a to avoid that error?

Also, the method definition starts_with_a has a . before the ===, although the variable starts_with_a does not. There's an error if I leave out that . in the method definition.

Question 2: what is happening with that .? why is it necessary etc.

sawa
  • 165,429
  • 45
  • 277
  • 381
BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134
  • See also http://stackoverflow.com/questions/13706373/what-does-def-self-function-name-mean/13709911#13709911 – BernardK Dec 29 '12 at 08:46

1 Answers1

0

With def starts_with_a. ===(e), you are defining a singleton method === on the object starts_with_a. The . between the object and the method indicates that it is a method defined on that object. If you do not have such object already created, a singleton method cannot be defined on it, and will return an error.

sawa
  • 165,429
  • 45
  • 277
  • 381