# 変数の例 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) (1..n).inject{|a,b| a*b} end factorial(10) factorial(100) # 進んで考えたい人のために 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) # 浮動小数点型 Ruby の場合 printf("%.50f\n", 1.0/3) # 複雑な式 Math.sin(Math::PI * 0.1) + Math.exp(Math.log( Math::PI + 0.1)) # 論理式 3 == 3 3 > 2 and 4 > 3 "abc" == "abc" or "xyz" == "XYZ" # if then else end x=-10 if x<0 then -x else x 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 # 複雑な論理式 Math::PI > 3.14 and ( Math::E > 2.7 or 3 != 2 or Math.sin(3.4) > 0.0 ) # if then else end x=3 y = if x==3 then 4 else 6 end x=4 y = if x==3 then 4 else 6 end # もっと複雑な式 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