Trans
8/30/2006 6:02:00 PM
ara.t.howard@noaa.gov wrote:
> harp:~ > cat a.rb
> class Array
> def self.step i, *a, &b
> j, s, ignored = *a
> i, j = 0, i if j.nil?
> s ||= (j < i ? -1 : 1)
> list = new
> i.step(j,s){|k| list << k}
> list.map! &b if b
> list
> end
> end
>
> require 'irb/xmp'
>
> xmp 'Array.step(0,4)'
> xmp 'Array.step(0,-4)'
>
> xmp 'Array.step(1,5,2)'
> xmp 'Array.step(-1,-5,-2)'
>
> xmp 'Array.step 2'
> xmp 'Array.step -2'
>
> xmp 'Array.step(0,7){|i| 2 ** i}'
> xmp 'even = Array.step(9){|i| i.modulo(2).zero?}'
>
>
>
> harp:~ > ruby a.rb
> Array.step(0,4)
> ==>[0, 1, 2, 3, 4]
> Array.step(0,-4)
> ==>[0, -1, -2, -3, -4]
> Array.step(1,5,2)
> ==>[1, 3, 5]
> Array.step(-1,-5,-2)
> ==>[-1, -3, -5]
> Array.step 2
> ==>[0, 1, 2]
> Array.step -2
> ==>[0, -1, -2]
> Array.step(0,7){|i| 2 ** i}
> ==>[1, 2, 4, 8, 16, 32, 64, 128]
> even = Array.step(9){|i| i.modulo(2).zero?}
> ==>[true, false, true, false, true, false, true, false, true, false]
I like it. Although also:
require 'facet/interval'
Interval.new(0,4).to_a => [ 0, 1, 2, 3, 4]
Interval.new(0,4).to_a(2) => [ 0, 2, 4 ]
etc. And it has many other applications.
T.