2 ms·
I hear you, and I realize Rubyists tend to avoid ternary operators, but I think this case is one where idiomatic Ruby makes unnecessary compromises against read
by stephth 14y ago
I hear you, and I realize Rubyists tend to avoid ternary operators, but I think this case is one where idiomatic Ruby makes unnecessary compromises against readability. Your arguments still don't convince me the latter is more readable.
Ruby Idiom: "Return symbol foo_matches if instance variable foo equals symbol bar"
You forgot the "else, it doesn't get called and the method returns nil by default" part. Although it's implicit, it doesn't mean you don't have to reason about it. On top of that, being implicit raises the barrier of understanding.
you may have to pause a bit longer on them since the ? and colon are frequently used for query-style methods and symbols respectively
I copy pasted from the article but I agree that readability could be improved with parentheses:
(@foo == :bar) ? :foo_matches : nil
I don't think the colon is a problem for readability either, being surrounded by spaces. I'll give you that a programmer coming from another language may make the mistake to think the space is optional.
- saraid216 14y agoThe ternary is generally a problem for readability. Ruby's particular style (like being able to return a value from an if-block) generally make the cases where they're useful obsolete. In this case, if we cared about readability, we wouldn't use a ternary at all: if @foo == :bar :foo_matches else nil end Which simplifies down to the exact refactoring offered.
- ZeroGravitas 14y agoIn Kent Beck's Smalltalk Patterns book he suggest that although every method returns "self" if you actually intend for that value to be used you should return it explicitly. I believe it's called the "Interesting Return Value Pattern' and I think the same applies here, the nil should be explicit.