make an exmpersion simpler

M

Michal Burak

Any way to make this shorter?

list2 << list1 if list1 && !list1.empty?

Thanks.
 
A

Aldric Giacomoni

Michal said:
Any way to make this shorter?

list2 << list1 if list1 && !list1.empty?

Thanks.

You want to add a list as an element to another list?
Just making sure we're talking about the same thing.
 
J

Jeremy Woertink

Michal said:
Any way to make this shorter?

list2 << list1 if list1 && !list1.empty?

Thanks.

if you know list1 will never be nil, then you can do

list2 << list1 unless list1.empty?


~Jeremy
 
A

Aldric Giacomoni

Tor said:
Michal said:
i wan add all elements from list1 to list2

That is not what your code does.

This should work:

list2.concat(list1 || [])

If, however, we know that list1 _does exist_ as a variable, thenis all we need. If list1 does not exist, your code will return an error,
and so...This will concatenate list1 and list2, unless list1 does not exist, in
which case it'll return nil instead of an error, and list2 will remain
the same.
 
R

Robert Klemme

2009/11/20 Tor Erik Linnerud said:
Michal said:
i wan add all elements from list1 to list2

That is not what your code does.

This should work:

list2.concat(list1 || [])

Here's a variant which will avoid the creation of the empty array:

list1 and list2.concat list1

I would not explicitly check for empty list. Array#concat will handle
that efficiently in C code.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top