Project

General

Profile

Actions

Feature #9587

closed

Integer#times with optional starting value

Added by sawa (Tsuyoshi Sawada) about 10 years ago. Updated about 4 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:61233]

Description

Just like Enumerator#with_index takes an optional argument that specifies the initial value of the index, I would like to request that Integer#times take an optional argument that specifies the initial value. The usefulness of it is similar to that of with_index taking an argument. We sometimes want to repeat tasks a given number of times, and want to use an index not necessarily starting from 0.

6.times(1){|i| puts "Chapter #{i}"}

should give

Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6

with the return value 6. We can do it with 1.upto(6), or with #{i + 1} within the block, but giving the initial value to times is much easier.

Updated by marcandre (Marc-Andre Lafortune) about 10 years ago

How exactly would it be easier than 1.upto(6)?

Updated by sawa (Tsuyoshi Sawada) about 10 years ago

Marc-Andre Lafortune wrote:

How exactly would it be easier than 1.upto(6)?

When the start value is 1, the argument 6 of upto coincidentally matches what would be the receiver of times, and you may not see the benifit, but when it is some other value such as 5, then you would need to calculate that in mind:

5.upto(10) # Need to calculate 10 (= 5 + 6 - 1)
6.times(5) # This is easier

A use case maybe when you are writing labels for pagination buttons. You know the start value, say 17, and you want to display ten next pages. Then,

10.times(17){|i| ...}

would give i = 17, 18, ..., 26. Doing this with upto or addition to the index within a times block may be a cause of careless bugs. (In the code above, I used an explicit number 17, but in real code, it would perhaps be some variable.)

Updated by Eregon (Benoit Daloze) about 10 years ago

"10.times(17)" is 170 at me, so it definitely is not an option as an unnamed argument.

Updated by phluid61 (Matthew Kerwin) about 10 years ago

On Mar 3, 2014 10:25 PM, wrote:

"10.times(17)" is 170 at me, so it definitely is not an option as an
unnamed argument.

Strongly agree. Maybe suggest: 10.times(from: 17)

Updated by sawa (Tsuyoshi Sawada) about 4 years ago

I now think that writing as below is good enough:

6.times.with_index(1){|_, i| puts "Chapter#{i}"}

I withdraw this proposal. Please close it.

Actions #6

Updated by Eregon (Benoit Daloze) about 4 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0