Heesob Park
4/24/2009 5:55:00 AM
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? =C2=A0Actually, I'd be happy with just the index.
>
> Basically, I want the Ruby way to:
> 1) Given scalar s
> 2) Given array a1 =3D [] 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. =C2=A0I 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 >=3D 25 }.first
> =3D> 30
>>> [10,20,30,40,50].find_all{|item| item <=3D 25 }.last
> =3D> 20
>
> How do I get the matched indices? =C2=A0That is, without ugly loops.
>
irb(main):001:0> a =3D [10, 20, 30, 40, 50, 60]
=3D> [10, 20, 30, 40, 50, 60]
irb(main):004:0> (0...a.length).select{|x| a[x]>=3D25}.first
=3D> 2
irb(main):005:0> (0...a.length).select{|x| a[x]<=3D25}.last
=3D> 1
In ruby 1.9.x
irb(main):002:0> a.index{|x| x<=3D25}
=3D> 2
irb(main):003:0> a.rindex{|x| x>=3D25}
=3D> 1
Regards,
Park Heesob