Rubyでのインデントは何桁にするのが良いか
Rubyではインデントを2桁(半角スペース2つ)にするのが一般的なようだが、どうも「少なすぎない?」というのが前々から気になっていた。ということで、実験。
まずは普通に2桁で書いたもの。ネタは http://programming-languages.appspot.com/comparison/category/list から。
# ポーカーの手を判定する関数 def check_poker_hand cards suit_count = cards.collect {|c| c[0] }.uniq.length numbers = cards.collect {|c| c[1] }.sort if suit_count == 1 # スートが揃っている場合 case numbers when sequential? ; 'Straight Flash' when [1, 10, 11, 12, 13] ; 'Royal Straight Flash' else ; 'Flash' end else # スートが揃っていない場合 case numbers when sequential? ; 'Straight' else hash = Hash.new 0 numbers.each {|n| hash[n] += 1 } counts = hash.values.sort.reverse case counts # 数が同じカードの枚数で判定する when prefix?(4) ; 'Four of a Kind' when prefix?(3, 2) ; 'Full House' when prefix?(3) ; 'Three of a Kind' when prefix?(2, 2) ; 'Two Pair' when prefix?(2) ; 'One Pair' else ; 'No Pair' end end end end
うーむ、defやifやelseとendとの対応関係がぱっと見で分かるとは言いにくいし、コードが縦に細長くてバランスが悪い気がする。
次に、4桁にしてみる。
# ポーカーの手を判定する関数 def check_poker_hand cards suit_count = cards.collect {|c| c[0] }.uniq.length numbers = cards.collect {|c| c[1] }.sort if suit_count == 1 # スートが揃っている場合 case numbers when sequential? ; 'Straight Flash' when [1, 10, 11, 12, 13] ; 'Royal Straight Flash' else ; 'Flash' end else # スートが揃っていない場合 case numbers when sequential? ; 'Straight' else hash = Hash.new 0 numbers.each {|n| hash[n] += 1 } counts = hash.values.sort.reverse case counts # 数が同じカードの枚数で判定する when prefix?(4) ; 'Four of a Kind' when prefix?(3, 2) ; 'Full House' when prefix?(3) ; 'Three of a Kind' when prefix?(2, 2) ; 'Two Pair' when prefix?(2) ; 'One Pair' else ; 'No Pair' end end end end
おお、こっちの方が断然分かりやすいな。
3桁でも試してみる。
# ポーカーの手を判定する関数 def check_poker_hand cards suit_count = cards.collect {|c| c[0] }.uniq.length numbers = cards.collect {|c| c[1] }.sort if suit_count == 1 # スートが揃っている場合 case numbers when sequential? ; 'Straight Flash' when [1, 10, 11, 12, 13] ; 'Royal Straight Flash' else ; 'Flash' end else # スートが揃っていない場合 case numbers when sequential? ; 'Straight' else hash = Hash.new 0 numbers.each {|n| hash[n] += 1 } counts = hash.values.sort.reverse case counts # 数が同じカードの枚数で判定する when prefix?(4) ; 'Four of a Kind' when prefix?(3, 2) ; 'Full House' when prefix?(3) ; 'Three of a Kind' when prefix?(2, 2) ; 'Two Pair' when prefix?(2) ; 'One Pair' else ; 'No Pair' end end end end
これでもいいな。2桁と3桁との間に決定的な溝があるようだ(まあ、実際に50%も差があるし)。