Forum: Ruby including range error

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6b2144362fffd4f71cca755d4045846f?d=identicon&s=25 Josselin (Guest)
on 2007-06-16 11:41
(Received via mailing list)
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
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2007-06-16 11:49
(Received via mailing list)
Alle sabato 16 giugno 2007, Josselin ha scritto:
> 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
This topic is locked and can not be replied to.