I have a function where I call the object method on a new line:
def fn(str)
str.gsub('a', 'a1')
.gsub('b', 'b2')
end
All this is fine and dandy ... while I do not want to put a comment before calling the newline method.
def fn(str)
str.gsub('a', 'a1')
.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 one line, the error will disappear ...
def fn(str)
str.gsub('a', 'a1')
.gsub('b', 'b2')
end
What's going on here? I am using the Ruby version ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]).
Edit
The Ruby analyzer can get confused about where to look at the end of the statement. str.gsub('a', 'a1')the statement may be in itself, or it may be continued on the next line.
From the Python world, to get around this, you need to open the area with parentheses in order to know the parser:
def fn(str):
return (
str.replace('a', 'a1')
.replace('b', 'b2')
)
Python , Ruby - , .