Add to Array if...

February 22nd, 2007

Here is a real quick Ruby Idiom that is quite helpful.

Let’s say you have a shopping list that you have declared as an array and you want to add an item to your list. You’d first want to make sure that it isn’t on your list already. You don’t want to buy two or more jars of peanut butter!

1
2
  shopping_list = ['peanut butter', 'grape jelly', 'whole wheat bread']
  shopping_list |= ['peanut butter']

The first thing I did was create the array for my peanut butter and jelly sandwhich and then I proceeded to add peanut butter to my list, if it isn’t already on my list. Since it is, it was not added to my shopping list array.

Gotta love Ruby Idioms!

4 Responses to “Add to Array if...”

  1. John Nunemaker Says:

    Wow. I had no idea that |= was a method. I need to look through the ruby source a bit. Thanks for the tip.

  2. Robert Says:

    I had the same reaction when I first learned this snip – it’s a pretty cool little piece.

  3. Gil Says:

    Nice! Playing with it, I discovered that ”|=” will remove the element if it is repeated inside the array, so you can remove all repeated elements of an array by using a |= a.

    a = [1,2,3,3,3,4,5] a |= [3] #=>[1,2,3,4,5]

  4. Robert Says:

    Nice Gil, that’s awesome!

    This is exactly what I want this site to be, sharing knowledge and learning from each other by sharing our code and explanations of our code.

    Cool stuff Gil!

Sorry, comments are closed for this article.