Alan Matthews
Alan Matthews

Reputation: 41

How can a class have a method named end

In Sketchup ruby, the class Edge has a method named "end".

How does Ruby deal with this method name to not conflict with the protected keyword marking the blockend (eg if … end) ?

Upvotes: 3

Views: 95

Answers (2)

max
max

Reputation: 102222

How does Ruby deal with this method name to not conflict with the protected keyword marking the blockend (eg if … end)?

When using def the parser assumes that what follows is an identifier (a symbol of sorts) delimited by parens or whitespace. You can't dynamically assign method names with def (without using some form of eval).

define_method(:end){} takes a symbol (or a string) so there is no problem with using a reserved word here either.

But the methods can not be called with an implicit receiver as commonly done inside a class:

# ok
class Foo
  def end
  end

  def test
    # not ambiguous 
    self.end 
  end
end

# syntax error, unexpected keyword_end, expecting end-of-input
class Bar
  def end
  end

  def test
    end 
  end
end

You can call the method with an explicit reciever:

Foo.new.end

Or use dynamic calling with send or call.

class Foo
  def end
  end

  def test
    send(:end)
    method(:end).call
  end
end

You can also use keywords in instance (@end), class (@@end) and global ($end) variable names, as the sigil tells the parser that we are dealing with a variable but not for local variables which have no sigil.

Upvotes: 3

Jörg W Mittag
Jörg W Mittag

Reputation: 369536

How does Ruby deal with this method name to not conflict with the protected keyword

Easy: they aren't protected keywords. They are documented as keywords, but actually, in the parser, they aren't really. They are more like what C♯ calls "contextual keywords", i.e. they are only treated specially within a certain context.

Upvotes: 1

Related Questions