Make an exmpersion simpler

Any way to make this shorter?

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

Thanks.

···

--
Posted via http://www.ruby-forum.com/.

Michal Burak wrote:

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.

···

--
Posted via http://www.ruby-forum.com/\.

Michal Burak wrote:

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

···

--
Posted via http://www.ruby-forum.com/\.

list1 is a list
list1 can be nil
i wan add all elements from list1 to list2

···

--
Posted via http://www.ruby-forum.com/.

Michal Burak wrote:

i wan add all elements from list1 to list2

That is not what your code does.

This should work:

list2.concat(list1 || )

Tor Erik
http://tel.jklm.no/

···

--
Posted via http://www.ruby-forum.com/\.

Tor Erik Linnerud wrote:

Michal Burak wrote:

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, then

list2.concat list1

is all we need. If list1 does not exist, your code will return an error,
and so...

list2.concat list1 rescue nil

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.

···

--
Posted via http://www.ruby-forum.com/\.

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

···

2009/11/20 Tor Erik Linnerud <tel@jklm.no>:

Michal Burak wrote:

i wan add all elements from list1 to list2

That is not what your code does.

This should work:

list2.concat(list1 || )

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/