||= for arrays

Dear messageboard users
I am just wandering if there is any operator similar to the ||= for
arrays?

#DOES NOT WORK
test_array = []
test_array ||= [‘nothing…’]

#DOES NOT WORK EITHER
test_array = []
test_array ||<< [‘nothing…’]

You could write something like this:
test_array << [‘nothing…’] if test_array.size == 0

But that just doesn’t look half as good as any of the two above in my
opinion.

Best regards
Sebastian Probst E.

On 10/1/06, Sebastian Probst E. [email protected]
wrote:

test_array = []
test_array ||<< [‘nothing…’]

You could write something like this:
test_array << [‘nothing…’] if test_array.size == 0

But that just doesn’t look half as good as any of the two above in my
opinion.

The ||= operator checks that the variable in question evaluates to nil
(or false, I think).

So, its behaving exactly as expected, since an empty array is not nil or
false.

-ryan

On Sunday 01 October 2006 19:17, Sebastian Probst E. wrote:

Dear messageboard users
I am just wandering if there is any operator similar to the ||= for
arrays?

#DOES NOT WORK
test_array = []
test_array ||= [‘nothing…’]

test_array |= [‘nothing…’]

Array#| is the union operator.

Michael


Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/

Hi –

On Sun, 1 Oct 2006, Michael S. wrote:

test_array |= [‘nothing…’]

Array#| is the union operator.

The problem with that (at least potentially, depending on what else is
happening) is that it creates a new array object, rather than
modifying test_array in place.

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

2006/10/1, Sebastian Probst E. [email protected]:

You could write something like this:
test_array << [‘nothing…’] if test_array.size == 0

You could do:

array = []
=> []

array << ‘nothing’ if array.empty?
=> [“nothing”]

array << ‘something’ if array.empty?
=> nil

array
=> [“nothing”]

Thanks for all the answers!

Best regards
Sebastian

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs