Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

make an exmpersion simpler

0 views
Skip to first unread message

Michal Burak

unread,
Nov 19, 2009, 1:29:12 PM11/19/09
to
Any way to make this shorter?

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

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

Aldric Giacomoni

unread,
Nov 19, 2009, 1:47:15 PM11/19/09
to
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.

Jeremy Woertink

unread,
Nov 19, 2009, 4:16:02 PM11/19/09
to
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

Michal Burak

unread,
Nov 20, 2009, 4:52:05 AM11/20/09
to
list1 is a list
list1 can be nil
i wan add all elements from list1 to list2

Tor Erik Linnerud

unread,
Nov 20, 2009, 5:37:58 AM11/20/09
to
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/

Aldric Giacomoni

unread,
Nov 20, 2009, 8:07:30 AM11/20/09
to
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.

Robert Klemme

unread,
Nov 20, 2009, 8:50:45 AM11/20/09
to
2009/11/20 Tor Erik Linnerud <t...@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 || [])

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

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

0 new messages