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])
.
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.
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.)
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