R
Rich Morin
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:
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 (e-mail address removed)
http://www.cfcl.com/rdm/weblog +1 650-873-7841
Technical editing and writing, programming, and web development
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:
=> [nil]list_or_nil=nil => nil
[list_or_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 (e-mail address removed)
http://www.cfcl.com/rdm/weblog +1 650-873-7841
Technical editing and writing, programming, and web development