Forum: Ruby Replacement idiom for "list_or_nil.to_a"?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D4d28bd014f9e7324bad99dcc3b0d390?d=identicon&s=25 Rich Morin (Guest)
on 2007-05-25 12:16
(Received via mailing list)
Many scripting languages, including Ruby, will "do nothing
gracefully" when asked to iterate through an empty list.
That is, they iterate NO times.

However, many Ruby methods do not return empty lists when
nothing is found.  Instead, they return nil.  This means
that idioms such as:

  list_or_nil.each do |value|
    ...
  end

will fail.  As a workaround, I've been using this idiom:

  list_or_nil.to_a.each do |value|
    ...
  end


However, I gather that this will soon be deprecated:

  http://www.megasolutions.net/ruby/to_a-68350.aspx

This page suggests putting the list in brackets:

  [list_or_nil]

but this doesn't solve MY problem:

  >> list_or_nil=nil
  => nil
  >> [list_or_nil]
  => [nil]

because the loop will now run once with the value nil.
I really dislike having to wrap the iteration block in
an "if" block:

  if list_or_nil
    list_or_nil.each do |value|
      ...
    end
  end

and this is only marginally better:

  list_or_nil.each do |value|
    ...
  end if list_or_nil


I suppose I could define my own to_a method for nil,
but that seems a bit questionable, as well.  So, is
there a Better Way To Do It?

-r
--
http://www.cfcl.com/rdm            Rich Morin
http://www.cfcl.com/rdm/resume     rdm@cfcl.com
http://www.cfcl.com/rdm/weblog     +1 650-873-7841

Technical editing and writing, programming, and web development
9b905791cbdbb1af35b65e02c3217e23?d=identicon&s=25 micathom (Guest)
on 2007-05-25 12:26
(Received via mailing list)
>   list_or_nil.each do |value|
>     ...
>   end

If you really want the extra loop in each just to find out that
nothing has to be done, you could also do:

    (list_or_nil || []).each do |value|
        ...
    end
E0526a6bf302e77598ef142d91bdd31c?d=identicon&s=25 Daniel DeLorme (Guest)
on 2007-05-25 14:01
(Received via mailing list)
Rich Morin wrote:
> will fail.  As a workaround, I've been using this idiom:
>
>   list_or_nil.to_a.each do |value|
>     ...
>   end
>
> However, I gather that this will soon be deprecated:

Object#to_a will be deprecated but not nil.to_a, so the
idiom you have above works just fine. It will break if
list_or_nil is a non-array non-nil value but I think
that's as it should be.

Daniel
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-05-25 14:02
(Received via mailing list)
On 25.05.2007 12:13, Rich Morin wrote:
>   end
>   http://www.megasolutions.net/ruby/to_a-68350.aspx
>   => [nil]
>
> and this is only marginally better:
>
>   list_or_nil.each do |value|
>     ...
>   end if list_or_nil
>
>
> I suppose I could define my own to_a method for nil,
> but that seems a bit questionable, as well.  So, is
> there a Better Way To Do It?

Probably.  How do you like

list_or_nil and list_or_nil.each do |x|
   ...
end

Or

irb(main):001:0> class NilClass
irb(main):002:1> def each; self; end
irb(main):003:1> include Enumerable
irb(main):004:1> end
=> NilClass
irb(main):005:0> nil.each {|x| puts x}
=> nil
irb(main):006:0>

?

Kind regards

  robert
96931bfe0c2948f47a98e15ae52e5637?d=identicon&s=25 Chris Carter (cdcarter)
on 2007-05-25 14:06
(Received via mailing list)
On 5/25/07, Robert Klemme <shortcutter@googlemail.com> wrote:
> irb(main):001:0> class NilClass
> irb(main):002:1> def each; self; end
> irb(main):003:1> include Enumerable
> irb(main):004:1> end
> => NilClass
> irb(main):005:0> nil.each {|x| puts x}
> => nil
> irb(main):006:0>

That hack will also make nil.to_a => [].
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-05-25 18:08
(Received via mailing list)
On May 25, 8:05 am, "Chris Carter" <cdcar...@gmail.com> wrote:
>
> That hack will also make nil.to_a => [].

If the code will be reusable, that's a little too risky.

It would be interesting however for an object to exist, say Void.
Something like:

  class Void
    def method_missing(*args)
      void
    end
  end

  def void
    $void ||= Void.new
  end

  (list_or_nil || void).each { |x| p x }

Though, a core implementation of Void would be much more efficient b/c
it would not need to even bother with method_missing, and just know to
return void and move on.

Hmmm... actually this has been discussed in another context before
(Hash lookup) as Null. Looks like another good reason for it.

T.
D4d28bd014f9e7324bad99dcc3b0d390?d=identicon&s=25 Rich Morin (Guest)
on 2007-05-25 18:24
(Received via mailing list)
Thanks for the suggestions!  Here's a summary, with comments:

> foo.to_a.each            {|value| ... }

  This is what I was using.  It's nice to know that it's not
  going away, after all.


> foo.to_a.each            {|value| ... } if foo

  This moves the "if" clause away from the iteration, which
  might make it harder to see.  Also, it evaluates foo twice
  (could duplicate side-effects if foo is a method or be a
  performance issue id evaluating foo is expensive).


> foo and foo.each         {|value| ... }

  A bit wordy and obscure.  Also, it evaluates foo twice.


> class NilClass
>   def each; self; end
>   include Enumerable
> end
>
> foo.each                 {|value| ... }

  This shortens the usage code, but I don't like playing with
  the definition of NilClass.  Specifically, this might confuse
  a human reader or get in the way of code that already expects
  the current behavior.


> (foo || []).each         {|value| ... }

  This smells like line-noise, but is otherwise quite adequate.


> (foo || VOID).each       {|value| ... }
> (foo || void).each       {|value| ... }

  Aside from the line-noise issue, these seem similar to me.
  Both require the use of a supplementary definition, however,
  which the reader might have to loop up.


> Array(foo).each          {|value| ... }

  This seems like an improvement, from a clarity standpoint.


My preference, at this point, is for either:

> foo.to_a.each            {|value| ... }

> Array(foo).each          {|value| ... }

I think I prefer the latter, from a clarity standpoint.  Also,
the fact that to_a is being deprecated in other contexts might
confuse some readers.

If foo is a BIG array, there might be performance differences
between these two, but I'm loathe to second-guess interpreter
implementation issues of this sort...

-r
--
http://www.cfcl.com/rdm            Rich Morin
http://www.cfcl.com/rdm/resume     rdm@cfcl.com
http://www.cfcl.com/rdm/weblog     +1 650-873-7841

Technical editing and writing, programming, and web development
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-05-29 09:51
(Received via mailing list)
On 25.05.2007 18:23, Rich Morin wrote:
>   This moves the "if" clause away from the iteration, which
>   might make it harder to see.  Also, it evaluates foo twice
>   (could duplicate side-effects if foo is a method or be a
>   performance issue id evaluating foo is expensive).
>
>
>> foo and foo.each         {|value| ... }
>
>   A bit wordy and obscure.  Also, it evaluates foo twice.

This is an issue only if foo is a method that does a complex
calculation.

>   the current behavior.
>   Aside from the line-noise issue, these seem similar to me.
>
>> foo.to_a.each            {|value| ... }

This might create another object which might impose a performance hit.

>> Array(foo).each          {|value| ... }
>
> I think I prefer the latter, from a clarity standpoint.  Also,
> the fact that to_a is being deprecated in other contexts might
> confuse some readers.
>
> If foo is a BIG array, there might be performance differences
> between these two, but I'm loathe to second-guess interpreter
> implementation issues of this sort...

There will likely be a performance hit if foo is something different
than an array because then it will have to be converted to an array.

Kind regards

  robert
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-05-29 18:53
(Received via mailing list)
On May 25, 12:23 pm, Rich Morin <r...@cfcl.com> wrote:
>   might make it harder to see.  Also, it evaluates foo twice
> > end
>
> > foo.each                 {|value| ... }
>
>   This shortens the usage code, but I don't like playing with
>   the definition of NilClass.  Specifically, this might confuse
>   a human reader or get in the way of code that already expects
>   the current behavior.
>
> > (foo || []).each         {|value| ... }

A very common idiom in Ruby however.

>   This smells like line-noise, but is otherwise quite adequate.
>
> > (foo || VOID).each       {|value| ... }
> > (foo || void).each       {|value| ... }
>
>   Aside from the line-noise issue, these seem similar to me.
>   Both require the use of a supplementary definition, however,
>   which the reader might have to loop up.

This is a hypothetical. The significant advantage of "void" would come
from a core implementation which would be much more efficient than [].
(A "void" object would also have some other good uses however. hint
hint matz ;)

T.
C381828d1907912eab30cbe38d5ea245?d=identicon&s=25 Aníbal (Guest)
on 2007-05-30 12:16
(Received via mailing list)
list_or_nil.each do |value| unless list_or_nil.nil?

--
Aníbal Rojas
http://www.rubycorner.com
http://www.hasmanydvelopers.com
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2007-09-25 23:02
(Received via mailing list)
On 25/05/07, Rich Morin <rdm@cfcl.com> wrote:
> I suppose I could define my own to_a method for nil,
> but that seems a bit questionable, as well.  So, is
> there a Better Way To Do It?

If you're going to get a list or nil then I find it nice to wrap it in
the Kernel#Array() method. It will convert a nil to a an empty array
but will leave an array untouched:

irb(main):001:0> Array(nil)
=> []
irb(main):002:0> Array([1,2,3])
=> [1, 2, 3]

Farrel
This topic is locked and can not be replied to.