Re: use of "return"



Robert Klemme wrote:

Dirk Meijer wrote:


hi,
'return' is used to return a value, and end the method processing.
at the end of a method, 'return' is indeed not needed, and simply
that value will suffice, though i think a return looks nicer ;-)
a good example where a return is needed, is this:

 def method(arg)
   if arg.class==String
     return "invalid argument"
   end
   #rest of processing
 end

this looks a lot nicer than placing your entire method in if/else
code. greetings, Dirk.



In this case you wouldn't use return values to flag this error. It's is a typical case for exceptions.

def mett(arg)
 raise ArgumentError, "#{arg.inspect} is not a String" unless String ===
arg
 # further processing
end

And taking this even further, in the light of Duck Typing (TM) usually no
type checks of this kind are made at all. :-)

Kind regards

   robert




Indeed, arg.to_str would be a more consistent duck typecheck. (Le Groan, what gruesome terminoogy sees the light of day.)

David Vallner


.



Relevant Pages

  • Taint (like in Perl) as a Python module: taint.py
    ... The following is my first attempt at adding a taint feature to Python ... string to create a safe string from it. ... def replace: ...
    (comp.lang.python)
  • Memory Question
    ... I have wrote a helper to my program which monitors object count, memory utilization and a threshold of 10% to determine how many objects are sticking around and how many are being garbage collected. ... occured right before the original String count). ... def print_threshold_breakers hsh1, hsh2, threshold ... putsf 'Building mem usage', mem_usage ...
    (comp.lang.ruby)
  • Re: [QUIZ] Editing Text (#145)
    ... I start by partially implementing a string class that works equally ... a single "gap" and recirculates unused space better. ... def inspect ... # remove excess trailing space if too much ...
    (comp.lang.ruby)
  • Re: Named/positional method args
    ... duck-typing isn't going to do a bit of good ... if one of those is passed in instead of the String representation. ... def to_file; self end ... It's not really limiting to specify types in method interfaces. ...
    (comp.lang.ruby)
  • UnicodeEncodeError in Windows
    ... def getdamage: ... """reads each line of war report ... """Build a string from a warrior's stats ... As I understand it the error is related to the ascii codec being ...
    (comp.lang.python)