Let Me Be Me

大道無門千差有路。透得此關乾坤獨歩。

Ruby Style Guideの Prefer hogehoge over mogemoge

bbatsov/rubocop · GitHubという、rubyのコードがコミュ二ティベースのコーディングガイドラインに従っているかどうかをチェックできるツールがあります。

その中で、

Prefer reduce over inject.

という指摘があって、どうしてinjectは駄目でreduceは良いのかわからなかったのですが、

上記のコーディングガイドラインによると、

Prefer map over collect, find over detect, select over find_all, reduce over inject and size over length. This is not a hard requirement; if the use of the alias enhances readability, it's ok to use it. The rhyming methods are inherited from Smalltalk and are not common in other programming languages. The reason the use of select is encouraged over find_all is that it goes together nicely with reject and its name is pretty self-explanatory.

ということらしいです。

 つまり、collect, detectやinjectなどはsmalltalk由来のメソッドで、他の言語ではあまりメジャーなメソッド名ではないから、reduceを使えってことなんですかね。ここで終わっても良かったのですいが、気になったので全部調べようと思ったら、全部wikipediaに載ってましたね...。

Fold (higher-order function) - Wikipedia, the free encyclopedia

(foldrが無い言語もあるので、foldlだけ。reduceとかfoldとか入ってれば全部カウントしてる。重複有。)

fold 13 reduce 11 inject 3

 ということで、foldとreduceがメジャーなようですね。