Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a comment between an object and a method call on separate lines?

Tags:

ruby

I have a function where I'm calling an object method on a new line:

def fn(str)
  str.gsub('a', 'a1')
     .gsub('b', 'b2')
end

All of this is fine and dandy... until I want to put a comment before the newline method call.

def fn(str)
  # Replace 'a' with 'a1'
  str.gsub('a', 'a1')
     # Replace 'b' with 'b2'
     .gsub('b', 'b2')
end

Boom! Error.

SyntaxError: syntax error, unexpected '.', expecting keyword_end (SyntaxError)
    .gsub('b', 'b2')
         ^

And yet, if I put the comments on the same line, the error goes away...

def fn(str)
  str.gsub('a', 'a1')  # Replace 'a' with 'a1'
     .gsub('b', 'b2')  # Replace 'b' with 'b2'
end

What on earth is going on here? I'm using Ruby version ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]).

Edit

The Ruby parser may be getting confused about where to consider the end of the statement. str.gsub('a', 'a1') could be a statement on its own, or it could be continued on the next line.

Coming from the Python world, the way to get around that is to open a scope with parentheses to let the parser know:

def fn(str):
  return (
    # Replace 'a' with 'a1'
    str.replace('a', 'a1')
       # Replace 'b' with 'b2'
       .replace('b', 'b2')
  )

Python has no problem with the above input, but Ruby still throws the same error even with the parentheses clearly bounding the statement.

like image 349
mxxk Avatar asked Dec 25 '22 02:12

mxxk


1 Answers

If you put the period of the method call at the end of the first line instead of the beginning of the next, Ruby knows you're going to call a method eventually and is happy to let you comment meanwhile:

def fn(str)
  # Replace 'a' with 'a1'
  str.gsub('a', 'a1').
    # Replace 'b' with 'b2'
    gsub('b', 'b2')
end

I also find this easier to read, since the period at the end of the line tells me that the expression isn't finished yet. Besides, I put every other binary operator at the end of the line rather than at the beginning of the next (for the same reason); why make an exception for .? (I know it's not an operator, but it's punctuation between two identifiers, so it might as well be one as far as formatting is concerned.)

like image 100
Dave Schweisguth Avatar answered May 24 '23 17:05

Dave Schweisguth