user3007294
user3007294

Reputation: 951

How do I iterate a range of values?

I understand that:

array = [1,2,3,4,5]
array.each { |x| puts x } #=> 1,2,3,4,5

How do I get the same to read for an inclusive range?

When I put:

array = [1...5]
array.each { |x| puts x } 

I just get 1...5. I really want: 1,2,3,4,5.

Any ideas?

Upvotes: 1

Views: 68

Answers (2)

Peter Alfvin
Peter Alfvin

Reputation: 29389

1..5 and 1...5 are both examples of Ruby Range literals. [1...5] is an array with one element, a Range. You can create an Array from a Range with the .to_a method, as in (1..5).to_a

The parentheses around the range are important because of the relatively low precedence of the .. symbol.

Range values are also directly enumerable, like arrays, as in (1..5).each {|x| puts x}

Upvotes: 2

uncutstone
uncutstone

Reputation: 408

coding as follows:

(1..5).each { |x| puts x } 

Upvotes: 0

Related Questions