Techioz Blog

Rubyでネストされた配列を反復処理する

概要

test_scores = [
  [97, 76, 79, 93], [79, 84, 76, 79], [88, 67, 64, 76], [94, 55, 67, 81]
]

puts test_scores.any? do |scores|
  scores.all? { |score| score > 80 }
end

上記のコードをReplitとローカルマシン(WSL)で実行すると、出力は「true」であることがわかります。ただし、Odin プロジェクトと ChatGPT の説明によると、出力は「false」になるはずです。 Odin プロジェクトは、「これは非常に簡単に思えます。入れ子になった配列のスコアがすべて 80 を超えていないため、 false を返します。」と述べています。オーディンプロジェクトのリンク

解決策

これは do … end ブロックと { … } の優先順位の違いに関係していると思います。

puts test_scores.any? do |scores| scores.all? { |score| score > 80 } end

実際にやっているのは:

puts(test_scores.any?) do |scores| scores.all? { |score| score > 80 } end

その間

puts test_scores.any? { |scores| scores.all? { |score| score > 80 } }

する

puts(test_scores.any? { |scores| scores.all? { |score| score > 80 } })

これで問題が明確になることを願っています。