including range error

J

Josselin

I wrote the following command

myRanges = [(0...2), (2...5), (5...10), (10...15), (15...25)]

myRanges.each_pair {|index, aRange| index if aRange.include?(1)}
I would like to get 0 as a result since 1 is falling into the first range....

but I got an error

undefined method `each_pair' for [0...2, 2...5, 5...10, 10...15, 15...25]:Array

how should I write it, if I want to get the index of the range where a
given number is falling...

thanks for your help

joss
 
S

Stefano Crocco

Alle sabato 16 giugno 2007, Josselin ha scritto:
I wrote the following command

myRanges = [(0...2), (2...5), (5...10), (10...15), (15...25)]

myRanges.each_pair {|index, aRange| index if aRange.include?(1)}
I would like to get 0 as a result since 1 is falling into the first
range....

but I got an error

undefined method `each_pair' for [0...2, 2...5, 5...10, 10...15,
15...25]:Array

how should I write it, if I want to get the index of the range where a
given number is falling...

thanks for your help

joss

each_pair is not a method of Array. If you need both the index and the element
in the block, you need to use each_with_index, which passes the block the
element and the index. Your code would become:

myRanges.each_with_index{|aRange, index| index if aRange.include?(1)}

This removes the error, but doesn't give the result you expect, because
each_with_index returns the receiver (myRanges), in this case. If you want to
stop the iteration when a range including 1 is found, and return its index,
you need to break the loop explicitly:

myRanges.each_with_index{|aRange, index| break index if aRange.include(1)}

I hope this helps

Stefano
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top