Splatting in case statements

RedHanded � Wonder of the When-Be-Splat

I always feel like I’m playing catch up to Rubyists.

BOARD_MEMBERS = ['Jan', 'Julie', 'Archie', 'Stewick']
HISTORIANS = ['Braith', 'Dewey', 'Eduardo']

case name
when *BOARD_MEMBERS
"You're on the board! A congratulations is in order."
when *HISTORIANS
"You are busy chronicling every deft play."
end

That’s pretty damn cool. The thing about new languages is that when you’re learning to write with it, you’ll write it in the style of the old language that you’re use to. C programmers will write C++ as if it were C. Java programmers will write Python as if it were Java. Therefore, you might think that there isn’t much to be gained from the new language other than some syntactic sugar sprinkled here and there.

As least for me, being open to other constructs like blocks, closures written more like functional programming has lead to more succinct and readable code.

a = [1, 2, 3]
Hash[*a.collect { |v|
[v, v*2]
}.flatten]

I would have done this with a for loop before, and that’s probably less readable. But I have to admit, succinct code only has meaning if you know the vocab.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s