# 変数の例 x=25 print( "xの値は ",x," です" ) x=30 print( "xの値は ",x," に変わりました" ) x=20; print( "xの値は ",x," です" ) x=30; print( "xの値は ",x," に変わりました" ) x=20; print( "xの値は ",x," です" ); x=30; print( "xの値は ",x," に変わりました" ) # いろいろのデータを一つの変数に x=20; print( "x is now ",x ); x=3.14; print( " but x is now ",x ); x="Hi!"; print( " but now x is ",x ) # 進んで考えたい人のために def factorial(n) if n<=1 then 1 else n*factorial(n-1) end end factorial(10) def factorial(n) r=1; (2..n).each{ |i| r*=i }; r end factorial(10) def factorial(n) r=1; for i in 2..n; r*=i end; r end factorial(10) # 暇な人向けの問題 def fct(n,f=1) if n<=1 then f else fct(n-1,n*f) end end fct(10) def factorial(n) (1..n).inject{|x,y| x*y} end factorial(10) def factorial(n) eval( [*(1..n)].join("*") ) end factorial(10) factorial(100) # 浮動小数点型 Ruby の場合 printf("%.50f\n", 1.0/3) # 複雑な式 Math.sin(Math::PI * 0.1) + Math.exp(Math.log( Math::PI + 0.1)) # 代入演算子の例 x=10 x+=5 x x=10 x+=x*=x x x=10 x*=x+=x # 論理式 3 == 3 3 > 2 and 4 > 3 "abc" == "abc" or "xyz" == "XYZ" # 論理式の例 3 > 2 3 != 3 3 > 2 and 3 == 3 3 > 2 and 3 != 2 3 > 2 and 3 != 3 3 > 2 or 2 != 2 3 > 2 and 3 == 2 3 > 2 or 3 == 2 # if then else end@ if a > 0 then y = 3 else y = -3 end # if then else endA x=-10 if x<0 then -x else x end # if then else endB x = 5 if x % 2 == 0 then puts( x , "は偶数" ) else puts( x , "は奇数" ) end # if then else endC x = 15 if x % 3 == 0 then puts( x , "は3の倍数" ) else puts( x , "は3の倍数ではない" ) end x=3 y = if x==3 then 4 else 6 end x=4 y = if x==3 then 4 else 6 end x = 3 if x == 3 then y = 4 else y = 6 end x = 4 if x == 3 then y = 4 else y = 6 end # if then else endD year = 2012 if year % 4 == 0 then puts( year , "年は閏年" ) else puts( year , "年は閏年ではない" ) end # if then else endE x = "female" if x == "male" then puts( x , "は男性" ) else puts( x , "は男性ではない" ) end # if then else endF x="abcde" if x.length > 3 then print( "x > 3" ) else printf( "x <= 3" ) end # 複雑な論理式 Math::PI > 3.14 and ( Math::E > 2.7 or 3 != 2 or Math.sin(3.4) > 0.0 ) # もっと複雑な式 y = if Math.sin(Math::PI/4) >= 0.1 and ( if Math::E == 2.7 then 2 else 1 end ) > 1.5 then if Math.exp(0.5) >= 0.3 then 0.3 else 0.5 end else Math.log(23) end