The ||= and |= operators

We initialize a variable with a value with the operator |=, but the value is only assigned if the variable has not been initialized yet.

  # Forma mas o menos normal
  if not breakfast
     breakfast = :bacon
  end

  # Esta forma es mas concisa y mas parecida al lenguaje humano
  breakfast = :bacon unless breakfast

  #usando ||=
  breakfast ||= :bacon

With the ||= we can add an object to an array, but if the object is already present the array, the operation dosnt introduce repetition in the array.

    animals  = ['dog','cat']

    # usando un condicion
    animlas += ['dog'] unless animals.include? ('dog')

    # using |=
    >> animal = ['dog','cat']
    => ["dog", "cat"]

    >> animal |= ['cat']
    => ["dog", "cat"]

    >> animal |= ['cat']
    => ["dog", "cat"]

    >> animal += ['cat']
    => ["dog", "cat", "cat"]
Advertisements

No comments yet

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: