Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

数字のループ

More than 1 year has passed since last update.

何となくやってみました。5回の繰り返しです。すべてわかるでしょうか。

Ruby
$ pry
[1] pry(main)> 5.times {|i| puts i}
0
1
2
3
4
=> 5
[2] pry(main)> (1..5).each {|i| puts i}
1
2
3
4
5
=> 1..5
[3] pry(main)> 1.upto(5) {|i| puts i}
1
2
3
4
5
=> 1
[4] pry(main)> for i in 1..5
[4] pry(main)*   puts i
[4] pry(main)* end  
1
2
3
4
5
=> 1..5
[5] pry(main)> i = 1
=> 1
[6] pry(main)> while i <= 5
[6] pry(main)*   puts i
[6] pry(main)*   i += 1
[6] pry(main)* end  
1
2
3
4
5
=> nil
[7] pry(main)> def count(i)
[7] pry(main)*   return if i > 5
[7] pry(main)*   puts i
[7] pry(main)*   count(i + 1)
[7] pry(main)* end  
=> :count
[8] pry(main)> count(1)
1
2
3
4
5
=> nil
[9] pry(main)> co = Enumerator.new do |y|
[9] pry(main)*   i = 1
[9] pry(main)*   while i <= 5
[9] pry(main)*     y << i
[9] pry(main)*     i += 1
[9] pry(main)*   end  
[9] pry(main)* end  
=> #<Enumerator: ...>
[10] pry(main)> loop {puts co.next}
1
2
3
4
5
=> nil
[11] pry(main)> co = Enumerator.new do |y|
[11] pry(main)*   i = 1
[11] pry(main)*   loop do
[11] pry(main)*     y << i
[11] pry(main)*     i += 1
[11] pry(main)*   end  
[11] pry(main)* end  
=> #<Enumerator: ...>
[12] pry(main)> puts co.take(5)
1
2
3
4
5
=> nil
[13] pry(main)> puts 1.step.take(5)
1
2
3
4
5
=> nil

ふーんという感じでしょうか。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away