Search code examples
rubyarrayscoding-style

Ruby style for displaying long arrays


I am using rubocop to check the styling conventions of my code conform to best practices. I have an array of colors and want to know the best way to display them. I've read that lines should be less than 80 characters long, so I did this.

colors = [:light_red, :red, :pink, :orange, :light_yellow, :yellow,
          :light_green, :green, :light_blue, :blue, :white, :black]

I get the following exception message from rubocop

C: Align the elements of an array literal if they span more than one line

Does this mean, I should have done something like this

colors = [:light_red,
          :red,
          :pink,
          :orange,
          :light_yellow,
          :yellow,
          :light_green,
          :green,
          :light_blue
          :blue,
          :white,
          :black]

That takes up an awful lot of space, and I thought my way was more efficient.

What is the stylistic rule regarding displaying multiline arrays in ruby?


Solution

  • There are different thoughts about where to end a line, so I do not discuss that.

    In case you are going to change lines between the items in a list, one thing I can say is that, you should do so as well between the delimiter characters ([ and ] in this case) and the first/last item. Not:

    ....... [:foo,
             :bar,
             :baz]
    

    but:

    ....... [
              :foo,
              :bar,
              :baz,
            ]
    

    It is a convention to indent the items two spaces relative to the indentation level of the delimiters.

    Another tip is to add a comma after the last item as shown above. Although this is optional, and has no effect to the code, this will make it easier for you to later edit the list (change the order, add, delete the items, etc.).