From: shugo / po.aianet.ne.jp (Shugo Maeda) Subject: [ruby-list:7659] iteration with index (Re: How to write Perl's `@a[@b] = @c' in ruby) Date: Mon, 20 Apr 1998 23:04:07 +0900 > In message "[ruby-list:7628] Re: How to write Perl's `@a[@b] = @c' in ruby" > Shin-ichiro Hara <sinara / blade.nagaokaut.ac.jp> wrote: > > |Enumerable のメソッドの多くは「with_index 化」できるなあ、と考えて > |いて勘違いしてしまいました。一々メソッドを作らずにする with_index > |化するいいやり方って無いかしら。 > > class Object > def with_index(iterator, *args) > i = 0 > send(iterator, *args) do |*x| > result = yield(i, *x) > i = i.next > result > end > end > end > > とすれば、 > > p "foo bar baz".with_index(:gsub, /[a-z]+/) { |i, s| i.to_s } > #=> "0 1 2" 良いですねぇ。send の使い方を教えてもらいました。 と感心しただけではなんですので、自分でちょっと with_indexと別の方向に 考えを進めてみました。 class Object def iterate_with(klass, iterator, accumlate) obj = klass.new send(iterator) do |*x| result = yield(*x) obj = obj.send(accumlate, result) result end obj end end k = %w(a b c); v = %w(A B C) p k.iterate_with(Array, :each_with_index, :concat) { |x, i| [x, v[i]] } p k.iterate_with(Hash, :each_with_index, :update) { |x, i| {x=>v[i]} } # sendって普通のmethod callと比較してどれくらいの速度なんでしょう? -- 稲葉 浩人 (inaba / st.rim.or.jp)