# 回数が分かっている繰り返し@ 10.times { print( "やっほ〜 " ) puts( " Yee-ha! " ) } # 回数が分かっている繰り返しA 10.times { |i| print( i , "回目のこんにちは\n" ) } 10.times { |i| print( i+1 , "回目のこんにちは\n" ) } # 回数が分かっている繰り返しA' total = 0 10.times { |i| total += i } print( "合計は" , total ) # 回数が分かっている繰り返しA'' total = 0 10.times { |i| total += i+1 } print( "合計は" , total ) # 回数が分かっている繰り返しB 10.times{ |i| print( 10 ** i , "\n" ) } 10.times{ |i| print( 10 ** (i+1) , "\n" ) } 10.times{ |i| print( 10 ** i , "\n" ) break if i == 5 } # 回数が分かっている繰り返しC 10.times {|i| print i; puts "番目"} 10.times {|i| puts( "#{i} 番目" ) } 10.times {|j| puts "*"*j} # 回数が分かっている繰り返しD n=5 n.times {|k| print( " "*(10-k), "*"*k, "\n" ) } # 回数が分かっている繰り返しE n=10 n.times {|k| print( " "*(10-k), "*", "\n" ) } n=10 n.times {|k| print( " "*(10-k), "*", " "*k*2 , "*" , "\n" ) } # eachB (3..5).each{ |i| print( i , "\n" ) } (1..4).each{ |i| print( i*2+1 , "\n" ) } # eachB a=3 b=5 (a..b).each{ |i| print( i , "\n" ) } a=1 b=4 (a..b).each{ |i| print( i*2+1 , "\n" ) } # eachC (-3..3).each{ |i| print( i , "\n" ) } (3..-3).each{ |i| print( i , "\n" ) } # 変数範囲が決まっている繰り返し@ (0..9).each{ |i| print( 10 ** i , "\n" ) } # 変数範囲が決まっている繰り返しA (5..10).each {|i| print( i ) if i%2==0 then print( " は偶数" ) else print( " は奇数" ) end print( "\n" ) } # 変数範囲が決まっている繰り返しB n=gets.chomp.to_i m=gets.chomp.to_i total=0 (n..m).each { |i| total += i } print( n , "から" , m , "までの合計は" , total ) # 変数範囲が決まっている繰り返しD (-10..10).each{ |i| print( i , " " , i**2 , "\n" ) } (10..-10).each{ |i| print( i , " " , i**2 , "\n" ) } # 刻み幅に小数値を使用したい場合 11.times{ |i| print( i / 10.0 , " " , (i/10.0)**2.0 , "\n" ) } (0..10).each{ |i| print( i / 10.0 , " " , (i/10.0)**2.0 , "\n" ) } (0..100).each{ |i| x = i.to_f / 100 print( x, " " , x**2.0 , "\n" ) } (0..20).each{ |i| print( i / 2.0 , " " , (i/2.0)**2.0 , "\n" ) } (0..40).each{ |i| print( i / 4.0 , " " , (i/4.0)**2.0 , "\n" ) } # 擬似乱数A 30.times { if rand() > 0.5 then print( "1" ) else print( "0" ) end } 30.times { print rand(2) } 30.times { print( if rand() > 0.5 then "1" else "0" end ) } # 擬似乱数B s = 0 loop{ s = rand(6)+1 print( s , "\n" ) break if s == 6 } # 擬似乱数C 5.times{ s = rand(21)-10 print( s , "\n" ) } # 擬似乱数D 5.times{ s = rand(10)/10.0 print( s , "\n" ) } # 擬似乱数を用いた例@ total = 0 5.times{ x = rand(100) print( x , "\n" ) total += x } print( " 合計は" , total ) # 擬似乱数を用いた例A max = 0 5.times{ x = rand(100) print( x , "\n" ) if max < x then max = x end } print( " 最大値は" , max ) # 擬似乱数を用いた例B min = 999 5.times{ x = rand(100) print( x , "\n" ) if min > x then min = x end } print( " 最小値は" , min ) # 擬似乱数を用いた例C a = 0 b = 0 10000.times{ x = rand(2) if x == 0 then a += 1 else b += 1 end } print( " 0の出現回数 " , a , "回\n" ) print( " 1の出現回数 " , b , "回\n" ) # 擬似乱数を用いた例D ans=rand(100) loop{ print( "数字を入力して下さい\n" ) input = gets.chomp.to_i if ans == input then print( "正解\n" ) break elsif input > ans then print( "正解はその値よりも小さい\n" ) else print( "正解はその値よりも大きい\n" ) end }