You've got a lot of Gal

Yet another blog about Ruby, Rails, Javascript, Apple, Malteses and Shih-Tzus by Gal Steinitz

This site is completely static. It was last generated with Octopress and Jekyll on Apr 15, 2014 and hosted on github pages.

Array#onely for Ruby

How many times do you use some_array.first as a way to get at the one and only member of that array?

It always bugged me that this can be error prone - if the array has more than one component you’ll never know about it, and the .first method isn’t semantically describing what you are doing - grabbing the one and only member.

If you add this somewhere in lib/initializiers, you get the #onely! method

1
2
3
4
5
6
class Array
  def only!
    raise "called Array onely! with array of length #{self.length}" if self.length > 1
    self.first
  end
end

which provides a more semantic description of what you’re trying to do:

1
2
3
4
5
6
> [].onely!
 => nil
> [1].onely
 => 1
> [1,2,3].onely
RuntimeError: called Array#onely! with array of length 3

Update 4/15/2014: As pointed out by @adamwong246 - “only” (the original method name I used) is already in use by ActiveRecord. He suggests “onely!” which has a nice ring to it.