The following code works fine:
class String
def foo
next!
end
end
puts 'hh'.foo # hi
This one also works fine:
class String
def foo
self.next
end
end
puts 'hh'.foo # hi
But this one doesn't:
class String
def bar
next
end
end
# Invalid next (SyntaxError)
Why does Ruby use the next keyword here and raises SyntaxError even though I am working on String class?
With your first two examples, the Ruby parser is certain that you are calling methods since the next keyword can't be used that way.
With you third example, it looks like you are using the next keyword instead of calling a method. The parser can't know at this stage that you actually mean to call a next method (which might or might not exist).
Thus, you have to guide the parser to avoid these ambiguities. You can either use an explicit receiver as in your second example or use constructs such as send(:next) instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With