0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby]基礎から日記。ブロックに渡せば閉じなくていいってなんかすごい

Posted at

筑波大学の問題もうすぐ終わりの44、45番。

[Ruby-44]
io = open("foo.txt", "r")
while line = io.gets
	print(line)
end
io.close

これは分かりやすい。while trueなんていらんかったんや。

[Ruby-45]
open("foo.txt", "r"){|io|
	while line = io.gets
	print(line)
end
}
io.close

こちらはio.closeがいらないことにびっくりした。いったいどうなってるんだ、と『たのしいRuby』p.295を見ると、

openメソッドにブロックを渡せばcloseメソッドを省略することもできます。

だって。理屈はわからないけどすごいなあ。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?