3 ms·
I'm still trying to think of a situation where I want to know if someone has passed the default value or not. The method itself shouldn't care; it returns the
by damncabbage 14y ago
I'm still trying to think of a situation where I want to know if someone has passed the default value or not.
The method itself shouldn't care; it returns the same result regardless whether an argument was passed explicitly or not.
What am I missing? :(
- caiusdurling 14y agoThe one time I've used it seriously was a method that was given the returned body of a HTTP GET call. If I remember rightly it was automatically parsed if it was a JSON body, so you could quite rightly get a nil body back, and that wasn't considered an error. However, if the body failed to parse, it invoked this method without an argument (bad decision further up the call stack, but by the point I hit it I didn't have time to refactor around it right then. AFAIK it was changed later to be less shit code and do stuff properly.) So I wanted to know in that method if nil was passed in by argument (as the parsed body was nil), or if no argument was passed, at which point the argument was set to nil as the default value by ruby. Having ruby set a `default = true` if no argument was passed was pretty much the only way to get myself out of that hole right then. Of course, having been coded into that corner once, I'd never do it that way again, so I'm not sure I'll ever be in a corner I need to use it to get out of again. Still useful to have the technique in the back pocket though, just in case!
- Mon_Ouie 14y agoMethods that simply behave differently depending on whether or not an argument is given. For example, passing nil (or any other object) to inject is different from passing nothing. [1, 2, 3].inject(:+) [1, 2, 3].inject(0, :+) [1, 2, 3].inject(nil, :+) # doesn't work Rubinius uses a magic ``undefined`` value for this: def inject(initial=undefined, sym=undefined, &block)
- philh 14y agoYou might want a lookup method to usually throw an exception if it doesn't find anything, but sometimes return a user-specified default. It's problematic though, because writing a thin wrapper becomes a pain in the ass.
- damncabbage 14y agoI'd argue that it's really two functions: * One to do the lookup and potentially explode; this always takes an argument. * A second to provide the default. Have the caller call the appropriate one. User provides params[:search] (or some other "explicitly trying to search"), then call the first. If not, call the latter.