Created
April 4, 2013 21:05
-
-
Save alucky0707/5314340 to your computer and use it in GitHub Desktop.
RubyとPythonじゃデフォルト引数の値が評価されるタイミングが違うんだぜ ref: http://qiita.com/items/b8677ec1d692f074e66b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#スコープの関係でグローバル変数 | |
$msg = "Hello, Before World!" | |
def say(str = $msg) | |
puts str | |
end | |
say #=> Hello, Before World! | |
$msg = "Hello, After World!" | |
say #=> Hello, After World! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
msg = "Hello, Before World!" | |
def say(str = msg): | |
print(str) | |
say() #=> Hello, Before World! | |
msg = "Hello, After World!" | |
say() #=> Hello, Before World! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$msg = "Hello, Before World!" | |
def say(str = $msg) | |
puts str | |
end | |
say() #=> Hello, Before World! | |
$msg = "Hello, After World!" | |
say() #=> このタイミングで $msg が評価される | |
#=> よって Hello, After World! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#見ろよこいつ、デフォルト引数で再帰してやがる… | |
def fact(n,ret = n <= 1 ? 1 : fact(n-1) * n) | |
ret | |
end | |
puts fact(10) #=> 3628800 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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