カテゴリー
未分類

Rubyで遊んでました。Ruby-list:241 コンスタント

[code lang=”ruby”]

#定数は大文字のアルファベットで始まる名前で指定される。
#p FOO #未定義の定数へのアクセスはエラー
F00 = 5
p F00
#F00 = 10 #定義された定数への代入はエラー

module ConstTest
CONST1 = 1
CONST2 = 2
CONST3 = 3
print "L3 ", CONST1, CONST2, CONST3,"\n"
def const_test
print CONST1, CONST2, CONST3,"\n"
end
end
#print CONST1, CONST2, CONST3, "\n" #このままではエラー
include ConstTest #includeすればOK
print "L1 ",CONST1, CONST2, CONST3, "\n"
CONST1 = 100 #エラーにはならないが、
print "L2 "
const_test() #値に変更はない。

p ConstTest::CONST1;p ConstTest::CONST2; p ConstTest::CONST3;
#ConstTest::CONST1 = 100 #参照は出来るが代入は出来ない

=begin
上の例ではConstTestモジュールに対して
`::’を使うと定数,CONST1,CONST2,CONST3は参照できるが,
ConstTestをincludeしたクラスであるObjectに対して`::’でCONST2,
CONST3をアクセスできない(CONST1は再定義しているので参照でき
るのだが).

=end

[/code]

カテゴリー
未分類

Rubyで遊んでました。Ruby-list:236

[code lang=”Ruby”]

#ruby-list:236
#p foo ローカル変数は最初に代入が必要なのでアウト。エラーです。
p foo = 1 #=>これはセーフでしょう。1
i0 = 1; print i0;p defined? i0 #=>1"local-variable"
loop{i1=5; print i1; break}; p defined? i1 #=>5nil ilはloopを抜けると参照できない。

i = 0
p1 = proc{|n| p i = n}
p2 = proc{p i}
p1.call(5) #=>5
p i #=>5
p2.call() #=>5
#スコープを共有している手続きオブジェクトはローカル変数も共有している。

def foo
i = 15
get = proc{i}
set = proc{|n| i = n}
return get, set
end
p1 = foo; p2 = foo
p p1
p p2

begin #以下はエラーになります。beginとendの間
p1.call()
p2.call(2)
p1.call()
end

=begin
#意味不明です。
手続きオブジェクトで特別な点は,ローカル変数の共有はスコープ
から抜けても続くことだ.つまり,上の例におけるp1, p2がスコー
プの外に渡されてもローカル変数iの共有は続く(この場合,変数i
はp1,p2からしかアクセスできなくなる).
=end

[/code]

カテゴリー
Rubyスクリプト

Ruby-list Tutorial 200~

p Math.sqrt(2) #=>1.4142135623730951
p Math::PI #=>3.141592653589793

=begin
trap "SIGURS1", 'print "foobar"'
kill "SIGURS1", $$
=end

proc = proc{print "foo\n"}
proc.call #=>foo

p self #=>main

proc2 = proc{print "$x changed ";
print "$x = ",$x,"\n"
}
trace_var (:$x){
proc2.call #=>$x changed $x = 5
}
$x = 5
カテゴリー
未分類

試験です。

[code lang=”ruby”]

def Sq(n)
n * n
end
p Sq(5)
#=============================================================
class Test

def foo
print "foo\n"
end
private :foo

def bar
print "bar ->"
foo
end
end
test = Test.new
#test.foo() private :fooを付け加えたら直接呼べない
test.bar()

[/code]

今まではスクリプトをスクリーンショットで撮ってましたが、違う方法もあるようです。

inserted by FC2 system