ts wrote:
> >>>>> "H" == Harry Truax <htruax / stf.com> writes:
>
> H> But unfortunately $SAFE needs to be set to 3 which will
> H> preclude the use of eval( ).
>
>  Just switch to $SAFE = 4 (in a new thread), to make your eval
>

We watch and learn, ts  :-)

>
> Guy Decoux
>


Harry,

With that advice from Guy, your original code can be changed
to something like this:

#------------------------------------------------------------
$SAFE=3

box1_1 = '12.9'; box1_2 = '-7';      box1_3 = '33.7'
box1_4 = '5.8';  box1_5 = '1244.66'; box1_6 = '38.8'
box1_7 = '200';  box1_8 = '4.4';     box1_9 = '-23'

#
# Use of lambda (formerly proc), allows direct access to
# the box00_00 variables -- (difficult from a method).
#
box_value = lambda do | box |
  ret_ = nil
  Thread.new { $SAFE=4;  eval("ret_ = #{box}") }.join
  ret_.to_f
end

add_boxes = lambda do | box, step, last |
  box_pfx, box_num = box.match(/\A([a-z]+\d+_)(\d+)\z/)[1, 2]
  print 'Summing:'
  sum = 0
  box_num.to_i.step(last, step) do | box_n |
    box = "#{box_pfx}#{box_n}"
    print ' + ', box
    sum += box_value[box]
  end
  res = '%0.2f' % [sum]
  puts "\n          = #{res}"
end

add_boxes['box1_1', 4, 9]
add_boxes['box1_2', 2, 8]

#-> Summing: + box1_1 + box1_5 + box1_9
#->           = 1234.56
#-> Summing: + box1_2 + box1_4 + box1_6 + box1_8
#->           = 42.00
#------------------------------------------------------------


I really think that other responses were encouraging you to
consider some much better ways of approaching this problem,
but you stated your constraints very clearly :(

Using a combination of a hash with keys of (e.g.) :box1_6
and the trick below, you might be able to convince your
superiors that the constraints would still be intact.


#------------------------------------------------------------

HBox = {:box10_27 => 4.16, :box11_29 => 11.2}

class Object
  def method_missing(meth)
    bm = meth.to_s.match(/\A([a-z]+)(\d+)_(\d+)\z/) or super
      p bm.to_a
    HBox[meth]
  end
end

p box10_27
p box11_29
p box100_100
p blah

#-> ["box10_27", "box", "10", "27"]
#-> 4.16

#-> ["box11_29", "box", "11", "29"]
#-> 11.2

#-> ["box100_100", "box", "100", "100"]
#-> nil

#-> C:/TEMP/rb8270.TMP:6:in `method_missing': undefined local variable or method 'blah' ...

#------------------------------------------------------------

Hope that's of some help,

:daz