3

I am trying to comment multiple lines in Rails 5 controller, I have searched the web and found the following solution: "=begin"

=begin (Multiple lines)
      respond_to do |format|
       if @person.update_attributes(params[:person])
        flash[:notice] = 'Person was successfully updated.'
        format.html { redirect_to(@person) }
        format.xml { head :ok }
       else
        format.html { render :action => "edit" }
        format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
       end
      end
=end

But it gives this error:

syntax error, unexpected '=' =begin

I am using Rails 5.0.

halfer
  • 19,824
  • 17
  • 99
  • 186
Amrinder Singh
  • 5,300
  • 12
  • 46
  • 88

4 Answers4

7

Ruby multi line comments only work when there is no whitespace between the start of the line and the =begin (the same applies to the =end). Make sure the line starts with =begin:

This works:

=begin
  foo
  bar
=end

This won't work:

  =begin
    foo
    bar
  =end
Sven Koschnicke
  • 6,523
  • 2
  • 34
  • 49
2

=begin and =end must not have any spaces before them

=begin
  code 
  I 
  want
  to 
  comment
=end

This is similar as commenting each line with #

# code 
# I 
# want
# to 
# comment
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
1

=begin and =end should be at same level of indentation of class. Like below

class MyController < ApplicationController
=begin
=end
end
pk-n
  • 568
  • 4
  • 11
1

In addition to other answers, multiline comment syntax in Ruby, although exists, is barely used. Some editors and syntax highlighters do not even recognize it. Your best bet is to use # on each commented line.

Additional benefit of using # is the option of nesting the comments, something not possible with =begin ... =end syntax.

respond_to do |format|
  if @person.update_attributes(params[:person])
    #  top level commented block
    #  flash[:notice] = 'Person was successfully updated.'
    #  # second level commented block
    #  # format.html { redirect_to(@person) }
    #  # format.xml { head :ok }
    # ...
  end
end

Your IDE should have no issues commenting/uncommenting a single comment level at a time.

See this SO question for the discussion.

Community
  • 1
  • 1
Nic Nilov
  • 5,056
  • 2
  • 22
  • 37
  • hmm, but if we deal with a huge code then commenting each line would not be a good idea, a lot of time will be wasted – Amrinder Singh Jul 28 '16 at 12:07
  • You should use your IDE's tools instead of manually typing every symbol. Multiline comment shortcuts are available basically everywhere. – Nic Nilov Jul 28 '16 at 12:09