News for hackers. Stuff that matters.
Re:Evil Ruby by damncabbage on Wednesday January 23, 2013 @07:12AM (#5102672)
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? :(

Re:Evil Ruby by Mon_Ouie on Wednesday January 23, 2013 @07:19AM (#5102697)
Methods 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)
Re:Evil Ruby by caiusdurling on Wednesday January 23, 2013 @07:18AM (#5102691)
The 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!

Re:Evil Ruby by philh on Wednesday January 23, 2013 @09:11AM (#5103051)
You 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.

Re:Evil Ruby by damncabbage on Wednesday January 23, 2013 @09:03PM (#5106661)
I'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.