2011年5月17日火曜日

Ruby 変数と定数とスコープ

puts "###############試験対策ソース###############"

puts "###############変数と定数とスコープ1###############"
x = 1
def ans
x = 4 #xを初期設定していない場合、xを呼び出す場合NameErrorが返されます。
puts x #=>4 xのスコープはメソッド内だけです。
end
ans
puts x #=>1


puts "###############変数と定数とスコープ2###############"

def ans2
x = 100 if false #この場合xへの代入は実行されないが、宣言はされます。
puts x #=>nil
end

ans2

puts "###############変数と定数とスコープ3###############"

def ans3
x = 0 #ブロックの外で初期設定
(0 ... 11).each do |i|
puts x += i #ブロック内でも有効です
end
end

ans3

puts "###############変数と定数とスコープ4###############"
def ans4
o = 0 #初期化を行っていない変数に代入を行うとNameErrarが吐き出されます。
for i in 1..10
o += i
end
puts o
end

ans4
★★★★★★実行結果★★★★★★
###############試験対策メ[ス###############
###############変数と定数とスコープ1###############
4
1
###############変数と定数とスコープ2###############
nil
###############変数と定数とスコープ3###############
0
1
3
6
10
15
21
28
36
45
55
###############変数と定数とスコープ4###############
55

0 件のコメント:

コメントを投稿