Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a class have a method named end

Tags:

ruby

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) ?

like image 992
Alan Matthews Avatar asked Jan 21 '26 23:01

Alan Matthews


1 Answers

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.

like image 107
max Avatar answered Jan 24 '26 18:01

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!