Hi!

* Imobach GonzáÍez Sosa:
> Hi all,
> 
> I've trying to find out how to check the class of a parameter. Right, I 
> talking about this:
> 
> class TestClass
>   # arg1 must be String instance
>   def myMethod(arg1, arg2)
>     # Code, code and more code.
>   end
> end
> 
> I think that I could solve in this way:
> 
> class TestClass
>   # arg1 must be a String instance
>   def myMethod(arg1, arg2)
>     if not arg1.kind_of?(String)
>       # Error! Some code must be added!
>     end
>    end
> end

Try this:

class TestClass
  def myMethod(arg1, arg2)
    unless arg1.class == String
      raise ArgumentError.exception('first argument must be string')
    end
    puts arg1, arg2
  end
end

Test:

test = TestClass.new
test.myMethod('foo', 'bar')
test.myMethod(1, 'bar')



> How could I assure that the parameter passed to myAttribute= method
> is Integer?

Why not? It is easy to define a setter:

class TestClass
  def myAttribute=(value)
    if value.class <= Integer
      @myAttribute = value
    else
      raise ArgumentError.exception('assignment requires integer')
    end
  end

  def myAttribute
    @myAttribute
  end
end

I did add a getter so that testing is possible.

test = TestClass.new
test.myAttribute = 10
puts test.myAttribute
test.myAttribute = 'foo'
puts test.myAttribute

Question to community: Raise an ArgumentError or a TypeError?

Josef 'Jupp' SCHUGT
-- 
http://oss.erdfunkstelle.de/ruby/    -     German comp.lang.ruby-FAQ
http://rubyforge.org/users/jupp/     -     Ruby projects at Rubyforge
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Germany 2004: To boldly spy where no GESTAPO / STASI has spied before