From: Josh Cheek Date: 2009-09-07T16:47:08+09:00 Subject: Re: Type checking function parameters --000e0cd5c6da6e4d430472f80eb0 Content-Type: text/plain; charset=ISO-8859-1 On Mon, Sep 7, 2009 at 2:12 AM, Nick Green wrote: > Lots of helpful opinions/philosophies about ruby here. > > As for the respond_to? is more useful than is_a? comment, I typecheck > almost everything with respond to (ok thats not really a "type"check... > i... check things with respond_to?) > > However, heres one issue I have, its not complicated, but its simpler to > say in code than words: > > def foo someint > someint+7 > end > > if foo "hello" > puts "hi" > else > puts "oh noez!" > end > > Putting this in irb only gives me an error. There are times I would > like to say, if this function works, do this, otherwise, do this. And > its not neccesarily unacceptable for the function to fail, but I wan't > to know if it failed so I can do something about that. I realize that > many (most?) functions you just figure its bad news if it fails, but I > have enough functions that I just redo/try something else/figure out > whats wrong if the function fails that I need a way to say this. In > less fun/happy languages this looks like > > > ret = putButterOn(my_pancake); > if (ret != BUTTER_APPLIED) > { > buttering_queue.enqueue(my_waffle); > return ERROR_PANCAKE_NOT_BUTTERED; > } > > And here, if I don't really have my heart set on a buttered pancake, > but I need to know if this putButterOn function was not build to handle > pancakes (perhaps pancake.respond_to? "spreadButter" == false). I > realize this code is not really a likely way to handle things, but it > gets the idea across. If I don't manually check values and return > nil/false/an error code if things go wrong, how can I keep going if a > function call fails? This works for checking errors in irb, but an > actual script appears to give up when it errors... > > ret = putButterOn my_pancake > if ret == nil > butter_queue.push my_waffle > end > -- > Posted via http://www.ruby-forum.com/. > > Maybe something like this: def foo someint someint+7 end begin foo "hello" puts "hi" rescue puts "oh noez!" end Personally, I've been wondering what would happen if nil just returned nil for every undefined method. Essentially, instead of always having to put if x && x.value && x.value > 3 I could just put if x.value > 3 because if x was nil, then nil.value would be nil, and nil.>(3) would be nil. I just wonder if this would break things, or is a naive question to ask, so I've been a little silent about it. But it keeps coming back to me, because a lot of edge case errors revolve around nil not responding to methods. --000e0cd5c6da6e4d430472f80eb0--