Ruby style for displaying long arrays

谁都会走 提交于 2019-12-11 12:26:36

问题


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?


回答1:


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.).




回答2:


Batsov describes this in https://github.com/bbatsov/ruby-style-guide#align-multiline-arrays. Looks like your variant is correct. Maybe you have changes over default rules for robocop?




回答3:


In v2.3 you'll be able to use Enumerable#tinyfy:

p colors.tinyfy(1)

[:light_red, :red, :orange, :light_yellow, :yellow, :light_green, :light_blue, :blue, :white, :black]

p colors.tinyfy(2)

[:light_red, :red, :orange, :light_yellow, :yellow, :light_green, :light_blue, :blue, :white, :black]

p colors.tinyfy(3)

[:light_red, :red, :orange, :light_yellow, :yellow, :light_green, :light_blue, :blue, :white, :black]

p colors.tinyfy(4)

[:light_red, :red, :orange, :light_yellow, :yellow, :light_green, :light_blue, :blue, :white, :black]

p colors.tinyfy(10)

..........



来源:https://stackoverflow.com/questions/29235927/ruby-style-for-displaying-long-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!