Bug #2533

sample/occur2.rb is old-fashioned

Added by yugui (Yuki Sonoda) over 2 years ago. Updated about 1 year ago.

[ruby-dev:39927]
Status:Closed Start date:12/27/2009
Priority:Normal Due date:
Assignee:matz (Yukihiro Matsumoto) % Done:

100%

Category:-
Target version:1.9.2
ruby -v:ruby 1.9.2dev (2009-12-24 trunk 26168) [i386-darwin9.8.0]

Description

Kernel#splitが無くなったことでsample/occur2.rbが動かなくなっていたのでr26180で修正しました。

それにしてもsample/occur2.rbは、今から見るとあまり良くないように思えます。
暗黙の変数を使うあたりがあまり現代Ruby的でなく、無意味にNil#+(Integer)のNameErrorでキーの不在をフォローしているのが教育上好ましくないと思います。
例外を使ってみるとか、何らかの意図があったんでしょうか。

現代語としては次のようになるのが自然ではないかと思いますが、いかがでしょうか。もし良ければ差し替えたいと思います。

diff --git a/sample/occur2.rb b/sample/occur2.rb
index 22cf520..ca87d0d 100644
--- a/sample/occur2.rb
+++ b/sample/occur2.rb
@@ -1,13 +1,10 @@
 # word occurrence listing
 # usege: ruby occur2.rb file..
 freq = {}
-while gets()
-  for word in $_.split(/\W+/)
-    begin
-      freq[word] += 1
-    rescue NameError
-      freq[word] = 1
-    end
+ARGF.each_line do |line|
+  for word in line.split(/\W+/)
+    freq[word] ||= 0
+    freq[word] += 1
   end
 end

Associated revisions

Revision 26188
Added by yugui (Yuki Sonoda) over 2 years ago

* sample/occur2.rb: reimplemented in modern style. [ruby-dev:39927].

History

Updated by matz (Yukihiro Matsumoto) over 2 years ago

まつもと ゆきひろです

In message "Re: [ruby-dev:39927] [Bug #2533] sample/occur2.rb is old-fashioned"
    on Sun, 27 Dec 2009 09:25:56 +0900, Yuki Sonoda <redmine@ruby-lang.org> writes:

|Kernel#splitが無くなったことでsample/occur2.rbが動かなくなっていたのでr26180で修正しました。
|
|それにしてもsample/occur2.rbは、今から見るとあまり良くないように思えます。
|暗黙の変数を使うあたりがあまり現代Ruby的でなく、無意味にNil#+(Integer)のNameErrorでキーの不在をフォローしているのが教育上好ましくないと思います。
|例外を使ってみるとか、何らかの意図があったんでしょうか。
|
|現代語としては次のようになるのが自然ではないかと思いますが、いかがでしょうか。もし良ければ差し替えたいと思います。

いいんじゃないでしょうか。

Updated by yugui (Yuki Sonoda) over 2 years ago

  • Status changed from Open to Closed
  • % Done changed from 0 to 100
This issue was solved with changeset r26188.
Yuki, thank you for reporting this issue.
Your contribution to Ruby is greatly appreciated.
May Ruby be with you.

Also available in: Atom PDF