Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the `next` method in Ruby raises SyntaxError while `next!` or `self.next` don't while monkey patching the String class?

Tags:

ruby

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?

like image 460
S.Goswami Avatar asked Feb 10 '26 20:02

S.Goswami


1 Answers

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

like image 98
Holger Just Avatar answered Feb 14 '26 22:02

Holger Just



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!