以下はdivmodを使い、変数xを7で割った商と余りを出力させるソースです。
ここに、divmodで返された配列[(商),(余り)]
に処理を加えたい(余りが0でないかつ最小のハッシュ要素のみを残したい)のですが、どのように書けばよろしいでしょうか。
rb
1hash = Hash.new(0) 2 3for x in 1 .. 10 4 if 7/x != 0 5 p ("#{7.divmod(x)} when x = #{x}") 6 hash[x] = 7.divmod(x) 7 end 8end 9 10puts hash 11 12# "[7, 0] when x = 1" 13# "[3, 1] when x = 2" 14# "[2, 1] when x = 3" 15# "[1, 3] when x = 4" 16# "[1, 2] when x = 5" 17# "[1, 1] when x = 6" 18# "[1, 0] when x = 7" 19# {1=>[7, 0], 2=>[3, 1], 3=>[2, 1], 4=>[1, 3], 5=>[1, 2], 6=>[1, 1], 7=>[1, 0]}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。