LoginSignup
0
0

More than 1 year has passed since last update.

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

next (Python)

a = iter([1, 2, 3, 4, 5])

while True:
    try:
        print(next(a))
    except StopIteration:
        break

# 1
# 2
# 3
# 4
# 5

独習Python 510p

初歩的なプログラミングでは、開発者がイテレーターを直接利用する機会はほどんどありません。

そうですよね、上記のプログラムであればforループで事足ります。

to_enum (Ruby)

a = [1, 2, 3, 4, 5].to_enum

while true
  begin
    puts a.next    
  rescue => exception
    break
  end
end

# 1
# 2
# 3
# 4
# 5

独習Ruby 278p

内部イテレーターでは表現しにくいものを(略)外部イテレーター(略)で表現

a = [1, 2, 3, 4, 5]

3.times do |i|
  puts a[i]
  i += 1
end

# 1
# 2
# 3

普通のループメソッドですと、イテレーターを変更i += 1することができないので、そういう時に使用するのかもしれませんね。

メモ

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