Ross Bamford
2/5/2006 3:34:00 PM
On Sun, 05 Feb 2006 14:41:21 -0000, jonT <j@Tippell.com> wrote:
> I'd like to propose a new addition to the enum module.
>
> detect works great but doesn't supply the index of the match. It would
> be nice to have a method detect_index that returned the index rather
> than the object.
>
> Use example:
>
> irb(main):001:0> foo =`uptime`.strip.split(' ')
> => ["14:36:06", "up", "157", "days,", "16:59,", "35", "users,", "load",
> "average:", "0.54,", "0.31,", "0.27"]
> irb(main):002:0> bar=nil
> => nil
> irb(main):003:0> foo.each_with_index {|o,i| if o=="users,"; bar=i;
> break; end;}
> => nil
> irb(main):004:0> foo[2..bar-2]
> => ["157", "days,", "16:59,"]
>
> Lines 2 to 4 would be expressed in a much more concise manner, i.e.
>
> irb(main):001:0> foo =`uptime`.strip.split(' ')
> => ["14:36:06", "up", "157", "days,", "16:59,", "35", "users,", "load",
> "average:", "0.54,", "0.31,", "0.27"]
> irb(main):002:0> foo[2..foo.detect_index {|o| o=="users,"}-2]
> => ["157", "days,", "16:59,"]
>
For this case, this might work?
foo[2..foo.index("users,")-2]
# => ["1", "day,", "14:18,"]
More generally, I'd personally like a block on 'index', such that:
foo.index("users,")
# => 6
foo.index { |s| s == "users," }
# => 6
Just MHO.
--
Ross Bamford - rosco@roscopeco.remove.co.uk