# Processing (potentially) nil method without using nested if

**URL:** <https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709>\
**Category:** Ruby\
**Created:** [June 5, 2010, 10:32pm UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709 "2010-06-05T22:32:58Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![ben-v](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ecb155/32.png) [@ben-v](https://www.ruby-forum.com/u/ben-v)\
**Post date:** [June 5, 2010, 10:32pm UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709/1 "2010-06-05T22:32:58Z")

</div>

Hi all,

really stupid question. How can I evaluate the following code without  
using a nested if… then statement?

if parent.respond\_to? “children”  
if parent.children.size != 0  
puts “Has children”  
end  
end

Ideally I’d like to do:

if parent.respond\_to? “children” && parent.children.size != 0  
puts “Has Children”  
end

But I get an error if parent.children is undefined. Isn’t there a way of  
stopping if the first condition is false?

Thanks,

Vish

---

<div class="post-metadata">

**Author:** ![ben-v](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ecb155/32.png) [@ben-v](https://www.ruby-forum.com/u/ben-v)\
**Post date:** [June 5, 2010, 10:55pm UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709/2 "2010-06-05T22:55:51Z")

</div>

On Jun 5, 1:33 pm, Ben V. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Ideally I’d like to do:
> 
> if parent.respond\_to? “children” && parent.children.size != 0  
> puts “Has Children”  
> end
> 
> But I get an error if parent.children is undefined. Isn’t there a way of  
> stopping if the first condition is false?

Hi Ben,

Because of precedence rules, your above code is being parsed as:

if parent.respond\_to?(“children” && parent.children.size != 0)  
puts “Has Children”  
end

“&&” and “and” have different precedence, and when leaving out  
parenthesis in function calls, it’s not as clear as to what’s going on  
(to the reader/writer). In this case, you can surround the two  
expressions with parenthesis, or use “and” instead.

> **[Ruby: operator precedence of && and = (which also applies to || or)](http://blog.jayfields.com/2007/08/ruby-operator-precedence-of-and-which.html)**
>
> Recently a bug popped up on my project surrounding code similar to the following sample. total = shopping\_cart . empty? and shopping\_cart ...

Mike

---

<div class="post-metadata">

**Author:** ![ben-v](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ecb155/32.png) [@ben-v](https://www.ruby-forum.com/u/ben-v)\
**Post date:** [June 5, 2010, 11:01pm UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709/3 "2010-06-05T23:01:16Z")

</div>

Ben V. wrote:

> Ideally I’d like to do:
> 
> if parent.respond\_to? “children” && parent.children.size != 0  
> puts “Has Children”  
> end
> 
> But I get an error if parent.children is undefined. Isn’t there a way of  
> stopping if the first condition is false?

Yes, but you’re being bitten by the ambiguity of what you’ve written,  
which is resolved by precedence rules. I’m not sure exactly how your  
code was being parsed, but I guess something like

if parent.respond\_to?(“children” && (parent.children.size != 0))

The rule is, if in doubt, add your own parentheses.

The following all work as you expect:

if (parent.respond\_to? “children”) && (parent.children.size != 0)  
puts “Has Children”  
end

if parent.respond\_to?(“children”) && parent.children.size != 0  
puts “Has Children”  
end

if parent.respond\_to? “children” and parent.children.size != 0  
puts “Has Children”  
end

The last of these works because ‘and’ has very low precedence, but I’d  
say it’s much better to be explicit with parentheses than clever with  
your knowledge of precedence rules.

Incidentally, it’s more idiomatic to use a symbol rather than a string  
for respond\_to?

if parent.respond\_to?(:children) …

Regards,

Brian.

---

<div class="post-metadata">

**Author:** ![ben-v](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ecb155/32.png) [@ben-v](https://www.ruby-forum.com/u/ben-v)\
**Post date:** [June 7, 2010, 11:24am UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709/4 "2010-06-07T11:24:50Z")

</div>

2010/6/5 Brian C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> Yes, but you’re being bitten by the ambiguity of what you’ve written,  
> puts “Has Children”  
> The last of these works because ‘and’ has very low precedence, but I’d  
> say it’s much better to be explicit with parentheses than clever with  
> your knowledge of precedence rules.
> 
> Incidentally, it’s more idiomatic to use a symbol rather than a string  
> for respond\_to?
> 
> if parent.respond\_to?(:children) …

It’s even more idiomatic to invoke a method and deal with the  
exception. Checking with #respond\_to? does not guarantee that the  
method can actually be executed.

In this case you could do

puts “Has Children” unless parent.children.empty? rescue nil

Or for a more targeted catch:

begin  
puts “Has Children” unless parent.children.empty?  
rescue NoMethodError

# OK, no output

end

Kind regards

robert

---

<div class="post-metadata">

**Author:** ![ben-v](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ecb155/32.png) [@ben-v](https://www.ruby-forum.com/u/ben-v)\
**Post date:** [June 7, 2010, 7:00pm UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709/5 "2010-06-07T19:00:54Z")

</div>

On 2010-06-07 02:24:26 -0700, Robert K. said:

> > if (parent.respond\_to? “children”) && (parent.children.size != 0)
> 
> exception. Checking with #respond\_to? does not guarantee that the  
> rescue NoMethodError
> 
> # OK, no output
> 
> end
> 
> Kind regards
> 
> robert
> 
> –  
> remember.guy do |as, often| as.you\_can - without end  
> [http://blog.rubybestpractices.com/](http://blog.rubybestpractices.com/)

Robert, you are correct in that “It’s even more idiomatic to invoke a  
method and deal with the exception” but rescue nil is a code smell that  
I would rather see avoided. A begin/rescue block also seems unnecessary.

Instead of solving a potential non-problem, I think it would be better  
to ask questions like… Why would this parent object not have a  
children method? Does this imply a design inconsistency? If parent can  
be nil, see the following.

In order to avoid NoMethodError on nil bugs, it’s most common to use  
&&, which short-circuits, as such:

parent.children && parent.children.size != 0

I may be assuming too much about your domain, but this seems more  
concise:

parent.children && !parent.children.empty?

Furthermore, it may be useful to ask: Why would children ever be nil?  
The empty array is a semantically correct way to say “no children”. If  
children were initialized to [], you could always ask children.empty?  
and skip the check for nil. For instance:

class Parent  
attr\_reader :children  
def initialize(children=[])  
@children = children  
end  
end

---

<div class="post-metadata">

**Author:** ![ben-v](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ecb155/32.png) [@ben-v](https://www.ruby-forum.com/u/ben-v)\
**Post date:** [June 7, 2010, 7:30pm UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709/6 "2010-06-07T19:30:39Z")

</div>

Hi all,

much thanks for all your help! The reason why I need to check if an  
object has a defined “children” method is because I have a bunch of  
classes, each with a parent and children until I get to the lowest  
level. Rather than defining the recursive function for all of them and  
modifying it for the lowest level, I can define one function and verify  
that children is defined at each iteration.

---

<div class="post-metadata">

**Author:** ![ben-v](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ecb155/32.png) [@ben-v](https://www.ruby-forum.com/u/ben-v)\
**Post date:** [June 7, 2010, 7:37pm UTC](https://www.ruby-forum.com/t/processing-potentially-nil-method-without-using-nested-if/189709/7 "2010-06-07T19:37:13Z")

</div>

On 07.06.2010 18:55, Rein H. wrote:

> > > > But I get an error if parent.children is undefined. Isn’t there a
> > > 
> > > if parent.respond\_to? “children” and parent.children.size != 0  
> > > if parent.respond\_to?(:children) …
> > 
> > begin  
> > puts “Has Children” unless parent.children.empty?  
> > rescue NoMethodError
> > 
> > # OK, no output
> > 
> > end

> which short-circuits, as such:  
> and skip the check for nil. For instance:
> 
> class Parent  
> attr\_reader :children  
> def initialize(children=[])  
> @children = children  
> end  
> end

Absolutely agree. At least the query for respond\_to? should be avoided  
since if the object does not have this method something more serious is  
wrong and an exception would be the proper result.

Often nil is used as initial value for efficiency reasons or reasons for  
simplicity (nil is the default for all values). So it may be  
appropriate to use it for empty collection of children as well. Other  
schemes could be devised as well, e.g. lazy initialization like

def children  
@children ||= []  
end

My main point when writing the earlier posting was that it is generally  
a bad idiom to check whether something can be done before doing it. The  
check gives only a false impression of safety since the operation can  
fail even if the check succeeds. So it’s generally better to just do it  
and deal with exceptions because even with a check you have to deal with  
the exception anyway. The check is basically just overhead.

Cheers

robert
