_

That nondescript title is not a placeholder – this post is really about the underscore. It arose out of one of those rewarding moments where you suddenly feel that there must be a way to do something better, and a search quickly reveals that, indeed, there is.

Ever evaluate a complex – particularly multi-line – expression in irb or Rails console and immediately after hitting the Return key realize that you’ve neglected to assign the return value to a variable? Suffer no more:

2.2.0 :001 > [[1,2], [3,4]].map do |pair|
2.2.0 :002 >   pair[0]*2 + pair[1]*3
2.2.0 :003 > end
=> [8, 18]
2.2.0 :004 > _
=> [8, 18]
2.2.0 :005 > _.map { |c| c*2 }
=> [16, 36]

See that little line on lines 4 & 5?! Saved by the humble underscore.

Advertisements
Tagged

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

%d bloggers like this: