Hi,

2009/4/24 Rob Redmon <rob.webinator / gmail.com>:
> How do I find matching expressions and return the match and the index of
> the match? Actually, I'd be happy with just the index.
>
> Basically, I want the Ruby way to:
> 1) Given scalar s
> 2) Given array a1 = [] which monotonically increases (e.g.
> [10,11,12,15,16,..])
> 3) Find the two elements in a1 who are nearest neighbors to the scalar
> s. I need the indices more than the values.
>
> Clearly, I can find the nearest values with this:
>>> [10,20,30,40,50].find_all{|item| item >= 25 }.first
> => 30
>>> [10,20,30,40,50].find_all{|item| item <= 25 }.last
> => 20
>
> How do I get the matched indices? That is, without ugly loops.
>

irb(main):001:0> a = [10, 20, 30, 40, 50, 60]
=> [10, 20, 30, 40, 50, 60]
irb(main):004:0> (0...a.length).select{|x| a[x]>=25}.first
=> 2
irb(main):005:0> (0...a.length).select{|x| a[x]<=25}.last
=> 1

In ruby 1.9.x
irb(main):002:0> a.index{|x| x<=25}
=> 2
irb(main):003:0> a.rindex{|x| x>=25}
=> 1

Regards,
Park Heesob