牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

簡単なカウンタをRubyとPythonで書いてみたメモ

その1

class Counter
  def up
    @count ||= 0
    @count += 1
  end
end

count = Counter.new
5.times do
  p count.up
end

#=> 1
#=> 2
#=> 3
#=> 4
#=> 5

もっと簡単に書けそうな気がする

その2(追記)

Google先生に聞いたら、自分のブログに書いてた

def counter(n)
  lambda { |i| n += i }
end

count = counter(0)
5. times do
  puts count.call(1)
end

#=> 1
#=> 2
#=> 3
#=> 4
#=> 5

Python

(python2.7.3)

from itertools import count

count = count(1)
for i in range(5):
    print(count.next())

#=> 1
#=> 2
#=> 3
#=> 4
#=> 5