Conversation
The documentation for this cop can be found at https://docs.rubocop.org/rubocop/cops_lint.html#lintsymbolconversion
|
Hey! Thanks for the suggestion. Maybe it's just me, but I haven't witnessed the mistake you mentioned. The quoted string notation for hash keys has been around for a while, since Ruby 2.2, and I can't recall seeing its usage when the intention was to have symbols as keys. I'm not saying that the mistake doesn't happen, I'm just trying to be mindful about introducing new rules to the style guide. |
What I've seen is the opposite: someone wants a Hash with String keys, but doesn't realize they need to use the "hash rocket" syntax for that, and ends up with buggy code like BEVERAGES_ENUM = {
"Apple Juice": 0,
"Chocolate Milk": 1,
"Beer": 2,
}
def beverage?(name)
BEVERAGES_ENUM.key?(name)
end
beverage?("Apple Juice") # false, because name is String, but key is SymbolIn this example,
In both cases, something now stands out, which might prompt the Ruby newcomer to research Hash keys and eventually change their code to be correct: BEVERAGES_ENUM = {
"Apple Juice" => 0,
"Chocolate Milk" => 1,
"Beer" => 2,
}Just seems like a simple foot-gun we can get rid of, the same way we've adopted parentheses. Arguably, this would be caught by writing good tests, but I don't see that as a reason not to enable the rule. Moreover, I don't see any reason why we would want to allow Symbol usage like |
Only Beer? If it is only it we might not have any advantage of enabling this cop since if "Beer" was a "IPA Beer" instead the entire hash would be valid in the view of this cop. |
|
Yeah, unfortunately I have been unable to find a way to strictly enforce the use of |
|
Can you check how many violations to this rule we have in Shopify core? |
What
This enables the
Lint/SymbolConversioncop.Why
A common mistake in Ruby is to assume that wrapping
SymbolHashkeys in quotes makes theHashuseStringkeys.This cop enforces the use of the simplest version of a Symbol possible, as shown in these examples from the documentation
This will incidentally catch Symbol Hash keys that are needlessly quoted, helping to prevent this mistake. The correction of other Symbols is a bonus.