On Sat, 17 Dec 2005, Caleb Tennis wrote:

> I have some methods in a class that look like this:
>
>  def h_coil(chan)
>    raise NoDataError if @h_coils[chan].nil?
>    @h_coils[chan]
>  end
>
>  def i_coil(chan)
>    raise NoDataError if @i_coils[chan].nil?
>    @i_coils[chan]
>  end
>
> and so on and so forth...
>
> I've been refactoring a bit to cut down on the redunancy in the code, and
> I'm wondering your thoughts on the best way of doing this, considering that
> all methods have the same "signature".
>
> Is define_method the smartest way?
>
> # pseudo code off the top of my head, probably has errors:
>
> def create_coil_method(name)
>  define_method(name) do |chan|
>    iv = ("@" + name.to_s + "s").to_sym
>    val = instance_variable_get(iv)
>    raise NoDataError if val.nil?
>    val[chan]
>  end
> end
>
> create_coil_method(:h_coil)
> create_coil_method(:i_coil)


you can certainly use metaprogramming here, but you could accomplish the same
effect with far less code:

     harp:~ > cat a.rb
     class Coil
       class NoDataError < StandardError; end

       attr "coils"

       def initialize
         @coils =
           Hash::new{|h,k| h[k] = Hash::new{|h,k| raise NoDataError, "chan=#{ k }"}}
       end
     end

     coil = Coil::new
     chan = 1
     coil.coils["z"][chan] = 42

     p coil.coils["z"][chan]

     p coil.coils["x"][chan]



     harp:~ > ruby a.rb
     42
     a.rb:8:in `initialize': chan=1 (Coil::NoDataError)
             from a.rb:18


regards.

-a
-- 
===============================================================================
| ara [dot] t [dot] howard [at] noaa [dot] gov
| all happiness comes from the desire for others to be happy.  all misery
| comes from the desire for oneself to be happy.
| -- bodhicaryavatara
===============================================================================