this is the first time i've encountered this pattern, and i've been writing ruby for a long time. i can understand why it's confusing. looks like a hacky way of early returning self when the method is called with no arguments. i don't understand why someone would write this over the following:

def clone(opts = nil)
return self if opts.nil?
...
end

there might be something i'm missing, but from messing around with it for a minute or two in irb, i can't tell a practical difference.

It's not exactly the same, because it also serves as an argument-count test. By which I mean, you'd potentially get a different result from object.clone(nil) than from object.clone, which is not the case if you test a nil default argument with nil?.

Of course in the OP code what you actually get from object.clone(nil) is a TypeError a couple of statements later, so we can't interpret this example as a deliberate arg-count guard. Maybe it benchmarked better, or maybe someone was just being clever, or maybe it's meant to give different results for object.clone vs object.clone({}).

NB: if you actually do want such a test, in general I'd rather use a private constant and test for identity in a guard clause, viz.

So as others have said, it returns self when called with no args, but the way it does it is by exploiting two things. One, that default argument values can be code (so you can write things like def whatever(thing = Thing.first)). And two, that code to provide a default argument only gets executed when it needs to kick in because the argument wasn't provided.

The reason it's two statements is that return self isn't actually providing a value. The interpreter will complain unless the expression has a value.

This is just way too clever in all the bad senses of the word. Who thinks putting flow control into the method definition itself is a good idea?

That’s a very shortsighted statement. It depends how often it comes into play. If you prolong Kernel#puts by some nanoseconds, noone will care. But increase Array#[] andHash#[] by the same amount, and people will start to notice.

As far as I understood, this tidbit is in Sequel, one of the main ORM layers in use by Rails; it gets invoked millions of times, in thousands upon thousands of servers. It’s definitely worth optimising.