从1开始循环 [英] Start a loop from 1

查看:89
本文介绍了从1开始循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近想到了一个可怕的想法:Ruby中的Integer.count循环从0开始并在与Facebook Engineering难题者一起玩时进入n-1.我做了一个肮脏的修复工作,即在开始时将一个添加到块变量中,以使它从一个开始.

I recently came upon the scary idea that Integer.count loops in Ruby start from 0 and go to n-1 while playing with the Facebook Engineering puzzlers. I did the dirty fix of adding one to the block variable in the beginning so that it would start at one instead.

有没有更漂亮的方法?

示例:

10.times do |n|
    n += 1
    puts n
end #=> 012345789

推荐答案

Ruby支持多种计数和循环方式:

Ruby supports a number of ways of counting and looping:

1.upto(10) do |i|
  puts i
end

>> 1.upto(10) do |i|
 >     puts i
|    end #=> 1
1
2
3
4
5
6
7
8
9
10

还有step而不是upto,它允许您以步进值递增:

There's also step instead of upto which allows you to increment by a step value:

>> 1.step(10,2) { |i| puts i } #=> 1
1
3
5
7
9

这篇关于从1开始循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆