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


i have function i'm calling object method on new line:

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

all of fine , dandy... until want put comment before newline method call.

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

boom! error.

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

and yet, if put comments on same line, error goes away...

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

what on earth 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 getting confused consider end of statement. str.gsub('a', 'a1') statement on own, or continued on next line.

coming python world, way around open scope parentheses let parser know:

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

python has no problem above input, ruby still throws same error parentheses bounding statement.

if put period of method call @ end of first line instead of beginning of next, ruby knows you're going call method , happy let comment meanwhile:

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

i find easier read, since period @ end of line tells me expression isn't finished yet. besides, put every other binary operator @ end of line rather @ beginning of next (for same reason); why make exception .? (i know it's not operator, it's punctuation between 2 identifiers, might 1 far formatting concerned.)


Comments