On Mon, 10 Dec 2001 17:28:06 +0100, Fabian Senftenberg <senf / kochfee.de>
wrote:

>Is there any way I can make sure that an expression (a block) is of a
>specific type? Suppose, I have a fancy little class like the
>following:
>
>class Interval
>  @start = Time.new()
>  @duration = 0
>
>  def initialize(s, d = 0)
>    @start = s
>    @duration = d
>  end
>
>  def end()
>    return #{@start + @duration}.usec
>  end
>end
>
>Now, the definition of the end method is not correct. Ruby complains
>with "undefined method `usec' for 0:Fixnum (NameError)". How may I
>tell the block "#{@start + @duration}" that is is of type Time and
>nothing else?

SInce all the code belongs to you, you need to ensure that the result of
the block returns what you want. I don't see in this case why you don't
just want to return

  (@start + @duration).usec

but if you want the block dragging around you could certainly put the
whole expression up above into the block.

A common way to ensure that calculations are of the correct type is to
provide conversion methods on all the interesting classes. See the
various to_a, to_s and so on.

As a matter of style, I would not implement my classes to check their
arguments: code with class-checking is generally considered tacky. I
might /convert/ arguments, for example something like

  def initialize(s, d = 0)
    @start = s.to_time
    @duration = d.to_i
  end

Then I'd write my code to work correctly without type-checking.

Just a matter of style, but I find it to be valuable. Perhaps you will
too.

Regards,

Ronald E Jeffries
http://www.XProgramming.com
http://www.objectmentor.com
I'm giving the best advice I have. You get to decide whether it's true for you.