LoginSignup
1
1

More than 1 year has passed since last update.

はじめに

移植やってます

yield (Python)

class A:
    def sequence():
        yield "1回目"
        yield "2回目"
        yield "3回目"

seq = A.sequence()
print(seq.__next__())
# 1回目
print(seq.__next__())
# 2回目
print(seq.__next__())
# 3回目

呼び出し側は、__next__()をやっているだけで、状態はレシーバが覚えています。

yield (Ruby)

class A
  def sequence
    Fiber.new do
      Fiber.yield "1回目"
      Fiber.yield "2回目"
      Fiber.yield "3回目"
    end
  end
end

seq = A.new.sequence()
puts seq.resume
# 1回目
puts seq.resume
# 2回目
puts seq.resume
# 3回目

上記プログラムで4回目の呼び出しを行うと、Pythonはエラー、Rubyはnilを返します。

メモ

  • Python の yield を学習した
  • 道のりは遠そう
1
1
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
1
1