Ruby Shortcuts

I sometimes stumble upon little snippets of ruby code that can replace longer loops. Like this one:

array.reject!(&:empty?)

which eliminates all empty strings from an array of strings (does not work for Fixnum), which is quite handy following a “split” operation.

Another one is this:

array.inject(:+)

which sums up all elements in an array and also works for strings.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s