Any way to make this shorter?
list2 << list1 if list1 && !list1.empty?
Thanks.
Any way to make this shorter?
list2 << list1 if list1 && !list1.empty?
Thanks.
Michal B. 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.
Michal B. 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
list1 is a list
list1 can be nil
i wan add all elements from list1 to list2
Michal B. 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/
2009/11/20 Tor Erik L. [email protected]:
Michal B. wrote:
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
Tor Erik L. wrote:
Michal B. 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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs