Hi,

At Mon, 20 May 2002 23:21:18 +0900,
wconrad / yagni.com wrote:
> > Interesting.  It's too hard to get an arbitrary binding, this
> > is possible.
> 
> I don't think I understand... could you please explain?

Once we talked about improvement of `binding' in ruby-dev, an
optional argument to specify the level.  If it were possible,
arbitrary bindings would be available, however it's difficult
to implement.

> > * added optional argument for stack_frames to restrict depth
> >   (and also to caller),
> 
> I think that's a good idea, in case of very deep recursion, but I
> didn't worry about it originally because I never recurse that deeply
> (I also noticed that #caller didn't worry about the stack being very
> deep).  Is that something we need today?

Maybe not, but it'll be more efficient in case of almost of
them won't be used.

> > # and imagined about optional arguments for Enumerable#to_a...
> 
> Sounds intriguing, but I can't imagine what it is.  Can you describe
> it more?

Enumerable#to_a(beg, len) returns Enumerable#to_a[beg, len] and
Enumerable#to_a(range) returns Enumerable#to_a[range].  Here is
an implementation example.

  module Enumerable
    alias __indefinite_to_a to_a

    def __definite_to_a(beg, len)
      ary = []
      last = beg + len
      each_with_index do |e, i|
        break if i >= last
        ary << e if i >= beg
      end
      ary
    end

    def __ranged_to_a(range)
      ary = []
      each_with_index do |e, i|
        if range === i
  	ary << e
        elsif !ary.empty?
  	break
        end
      end
      ary
    end

    def to_a(*args)
      case args.size
      when 2
        __definite_to_a(*args)
      when 1
        __ranged_to_a(*args)
      else
        __indefinite_to_a(*args)
      end
    end
  end


One possible usage is to make partial array from infinite
sequence.

  class Primes
    include Enumerable

    def each
      yield 2
      primes = []
      n = 3
      loop do
        unless primes.find {|i| n % i == 0}
  	primes << n
  	yield n
        end
        n += 2
      end
    end
  end

  Primes.new.to_a(2,3)	#=> [5, 7, 11]
  Primes.new.to_a(3..5)	#=> [7, 11, 13]


Another one:

  open("README").to_a(3, 4) # =>
["easy object-oriented programming.  It has many features to\n",
 "process text files and to do system management tasks (as in\n",
 "Perl).  It is simple, straight-forward, and extensible.\n",
 "\n"]


# But I've felt it isn't a good idea.

-- 
Nobu Nakada