Ruby opinions (111)

64 Name: dmpk2k!hinhT6kz2E : 2007-08-08 05:59 ID:Heaven

Anybody reading this thread might be convinced I detest Ruby.

But that ain't so!

So I'll share one feature of Ruby I wish I saw in more languages: ||=

||= is a cute little feature that checks whether a variable is nil, and assigns what's on the right-hand side if it is. So things like this:

if x

x += [ y ]

else

x = [ y ]

end

...can become this:

x ||= []
x += [ y ]

Five lines into two, and I suspect the latter is also a tad faster. I find myself often using things like "@@var ||= <x>" when caching the results of some expensive operation that's needed in a frequently-invoked method, and while the above example might seem a big usual (why not just x = [] before a loop?), I seem to get it a lot when processing arrays that contain arrays.

I cannot emphasize how much I like the ||= operator. It's a small thing, but oooooh aaaaaah. Now I just wish there were things like ||+= et alia...

Name: Link:
Leave these fields empty (spam trap):
More options...
Verification: