3 ms·
I liked their guideline on when to use bang methods like `array.map!` in ruby: "The names of potentially 'dangerous' methods (i.e. methods that modify self or
by mapgrep 15y ago
I liked their guideline on when to use bang methods like `array.map!` in ruby:
"The names of potentially 'dangerous' methods (i.e. methods that modify self or the arguments, exit!, etc.) should end with an exclamation mark. Bang methods should only exist if a non-bang method exists."
That last sentence finally made me understand why `string.gsub!` takes a bang but `FileUtils.rm_rf(dir)` does not, even though the latter is far more dangerous (in the generic case). It's not just about the danger level of the method but about the existence of a non-dangerous alternative. Now I've started noticing that some gems do not follow this guideline.
- mattbriggs 15y agofirst time i heard that was from greg browns Ruby Best Practices book (was probably the best thing I took away from it). At this point (unfortunately) bang means almost nothing, since the reason to use bang seems to be different for every rubyist
- gioele 15y agoExamples of different uses? The only example I know of is DataMapper that uses bang methods such as `save!` for the methods that change data bypassing the validation mechanism. But I would argue that this use fits the original definition quite nicely.
- petercooper 15y agoThere are lots of simpler examples too. Consider Array#push or Array#pop. Both make changes to an array in place, but are not ! suffixed due to the requirement you quoted. You are right, though. Many Rubyists do not follow this convention and often don't even know about it. It's a key convention of the core implementation team, however.
- obtu 15y agoI just realised this is the same rule as for bang commands in Vim and Pentadactyl.
- spacemanaki 15y agoDoes Ruby convention follow Lisp in regards to methods ending in a question mark too? In Clojure and Scheme those methods should return an actual boolean value and not truthy values or nil. Compare `some` and `every?` in Clojure: http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/every%3F http://clojure.github.com/clojure/clojure.core-api.html#cloj... http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/some http://clojure.github.com/clojure/clojure.core-api.html#cloj... And in Scheme `member` doesn't have a question mark for this reason, it returns the cdr of the list starting with the item if it's found. It's a subtle point, and probably trips up newcomers, but I think it's useful, especially since the types of methods and functions in these languages are not as well broadcast as in statically typed languages.