Skip to content

Instantly share code, notes, and snippets.

@maxim maxim/1-works_fine.rb
Last active Nov 28, 2016

Embed
What would you like to do?
Strange ruby bug: can't put comment after linebreak in method args. Tested in 2.3.2.
def foo \
a: 'a',
# comment here is ok
b: 'b'
puts a, b
end
foo(a: 'a', b: 'b') # => a\nb
def foo \
# comment here causes error
a: 'a',
b: 'b'
puts a, b
end
foo(a: 'a', b: 'b')
@apeiros

This comment has been minimized.

Copy link

apeiros commented Nov 28, 2016

since \ "escapes" the newline, what ruby sees in 2-broken.rb is:

def foo  # comment here causes error
  a: 'a',
  b: 'b'

  puts a, b
end

and that a: 'a', on the first line of what ruby considers to be the method body is a syntax error (syntax error, unexpected ':')

@maxim

This comment has been minimized.

Copy link
Owner Author

maxim commented Nov 28, 2016

@apeiros Yep, I understand what you mean. Here's another way to illustrate.

puts "foo"\
"bar"
# stdout => foobar


puts "foo"\
# comment
"bar"
# stdout => foo

It's also consistent with leading period, which "reaches" for exactly previous line, and doesn't tolerate comments either:

r = 
  "foo"
    .strip
    # comment
    .upcase
# => syntax error, unexpected '.', expecting end-of-input
r =
  "foo"
    .strip \
    # comment
    .upcase

puts r
# stdout => FOO
r =
  "foo"
    .strip \
    # comment
    # comment2
    .upcase
# => syntax error, unexpected '.', expecting end-of-input

But I'm curious why \ or leading period wouldn't gain the extra meaning of expecting next/previous line anywhere, bypassing comments.

@apeiros

This comment has been minimized.

Copy link

apeiros commented Nov 28, 2016

I see what you mean. Yeah, makes sense to allow \ to skip comments. Especially since you can't use \ in a comment to further continue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.