Hello --

On Sat, 28 Jul 2001, David Tillman wrote:

>   Hello all, I have been coding in Ruby for a few days now and have
>   some questions.

Always glad to see a new Dav* :-)

>   I understand (I think) about telling collect to an array as exhibited
>   by the table method below.
>
>   I would like to do something similar in the method table_fancy but
>   had to use a temp var, x, to make it work.
>
>   Any ideas on how I can eliminate the x?
>
>
> class Array

It seems a little sideways to add these methods to Array.  I think it
might be more logical to have the HTMLtable objects know how to
assemble themselves.  But anyway, let me address the question as it
stands.

[...]

>   def table_fancy (format, *args)
>
>     alf = HTMLtable.new(*args)
>     x = ''
>
>     self.each { |row| 0.upto (row.length - 1) { |i| x << tcell (row[i], *format[i]) }
>       alf << trow (x)

(Note: if you have a space between a method name and a parenthesized
argument list, you'll get a warning (when running under -w)).

>       x = ''}
>
>     alf.to_s
>
>   end
>
>
> end

In order to gather up the results of doing the tcell call over the
whole array, I think you'll need either a temporary variable or an
array method which will return a new array with those results.

#map (aka #collect) will do that, except you also need to keep track
of the indices for the purpose of stepping through "format".

Unfortunately, there's no #map_with_indices.  So you might want to use
this one:

  module Enumerable
    def map_with_indices
      res = []
      each_with_index do |e,i|
	res.push yield e,i
      end
      res
    end
  end

and then do something like this:

  def table_fancy(format, *args)
    HTMLtable.new(*args) << map {|row|
       row.map_with_indices {|c,i|
        tcell(c, format[i])
      }
    } .map {|x| trow(x)} .to_s
  end

which basically filters the array through the cell and row routines
and converts the results to a string.

(I keep staring at that and thinking there should be a way to reduce
it by about 40%, but pending that, see if it helps :-)

Another way: if you don't mind destroying "format", you could do:

   ...
   row.map { |c|
     tcell(c, format.shift)
   }
   ...

or dup format first (but then you have a temporary variable again :-),
or call the method with a dup of format.

(Sorry, this got longer than I'd expected.)


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav