Skip to content

Instantly share code, notes, and snippets.

@alucky0707
Created April 4, 2013 21:05
Show Gist options
  • Save alucky0707/5314340 to your computer and use it in GitHub Desktop.
Save alucky0707/5314340 to your computer and use it in GitHub Desktop.
RubyとPythonじゃデフォルト引数の値が評価されるタイミングが違うんだぜ ref: http://qiita.com/items/b8677ec1d692f074e66b
#スコープの関係でグローバル変数
$msg = "Hello, Before World!"
def say(str = $msg)
puts str
end
say #=> Hello, Before World!
$msg = "Hello, After World!"
say #=> Hello, After World!
msg = "Hello, Before World!"
def say(str = msg):
print(str)
say() #=> Hello, Before World!
msg = "Hello, After World!"
say() #=> Hello, Before World!
$msg = "Hello, Before World!"
def say(str = $msg)
puts str
end
say() #=> Hello, Before World!
$msg = "Hello, After World!"
say() #=> このタイミングで $msg が評価される
#=> よって Hello, After World!
msg = "Hello, Before World!"
def say(str = msg): #この時点で msg が評価されて Hello, Before World! になっている
print(str)
say() #=> Hello, Before World!
msg = "Hello, After World!"
say() #=> すでに str の値は決定しているから、 Hello, Before World!
#見ろよこいつ、デフォルト引数で再帰してやがる…
def fact(n,ret = n <= 1 ? 1 : fact(n-1) * n)
ret
end
puts fact(10) #=> 3628800
say_n = []
for i in range(0,10):
#say_n.append(lambda: print(i))
#だと i の値が更新されていってしまうためダメ
say_n.append(lambda j = i: print(j))
#のようにして、 i を束縛する必要がある
say_n[2]() #=> 2
say_n[4]() #=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment