What is the advantages of a literal for symbol array?

Hello everyone,

Could someone please advice what is the advantages of using a literal for the array of symbols?

%i{foo bar} #=> [:foo, :bar]

Particularly over just [:foo, :bar]

We started using HoundCI recently, where it complains:

Use %i or %I for array of symbols.

On the following line:

MINIMUM_ADDRESS_FIELDS = [:address_line_1, :city, :country, :post_code]

That literal was introduced in ruby 2.0 and as far as I can tell not quite popular yet :smile:

Thank you in advance!

I don’t think there’s any advantage. It’s just a difference in syntax.

I’ve never used HoundCI, but I believe it makes recommendations based on this Ruby style guide:

That style guide says: “Prefer %i to the literal array syntax when you need an array of symbols”.

Again, I think this is just a syntax difference. HoundCI is just making a style recommendation to be consistent with that style guide. Really there’s no difference between [:a, :b] and %i(a b)
Just like there’s no difference between [ ] and Array.new

Hi @yevgenko, everything @chris_sun1 said sounds right to me. Just a different syntax, not necessarily better (although it is easier to type, which is nice!) A major goal when using Hound is to encourage a consistent syntax which does not necessarily imply that the particular style Hound is enforcing is “better”.

All that said, you can modify the rules Hound will use when evaluating your code. Check out the docs on configuring the ruby style rules for help.

@chris_sun1, @christoomey thank you guys!

what is your preference [:a, :b] or %i(a b), some peoples found that [:a, :b] is more readable? :smile:

I like %i[a b] since the square brackets signify an array.

1 Like