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

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)
  # 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 one line, the error will disappear ...

def fn(str)
  str.gsub('a', 'a1')  # Replace 'a' with 'a1'
     .gsub('b', 'b2')  # Replace 'b' with '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 (
    # Replace 'a' with 'a1'
    str.replace('a', 'a1')
       # Replace 'b' with 'b2'
       .replace('b', 'b2')
  )

Python , Ruby - , .

+4
4

, , Ruby , :

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

, , , . , , ( ); .? ( , , , , ).

+5

gsub, Ruby , .

"hello".gsub('e','a')

       .gsub('l','w')

, , .

, ".",

+2

, , ...

# This works

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

This is an alternative to moving .to the end of the line, as suggested by Dave Schweisgut.

+2
source

@mksios

Please make changes to your code.

def fn(str)
    # Replace 'a' with '1' & Replace 'b' with '2'
    str.gsub('a', '1')
    .gsub('b', '2')
end

You pass gsub to change b on the next line. When you are not using a comment, then it treats it as a function, but when you add a comment above .gsub ('b', '2'), it breaks the syntax.

+1
source

Source: https://habr.com/ru/post/1653377/


All Articles