Reputation: 11121
If the results is nil then I get NoMethodError - undefined method 'length' for nil:NilClass:
Is there any way I don't have to use two conditions? I thought that ruby won't evaluate the second part of the condition in case results is empty because the condition can be never true.
if (not results.empty? && results[-1].length == 2)
(4-results[-1].length).times {|i| results[-1] << ""}
end
Upvotes: 0
Views: 61
Reputation: 160191
I'd consider changing it to something that IMO "reads" better:
if results.any? && (results[-1].length == 2)
...
end
To avoid two explicit conditions, install the andand gem:
pry(main)> require 'andand'
pry(main)> r1 = []
pry(main)> r2 = ["hi", "there"]
pry(main)> r3 = ["hi", "no"]
pry(main)> puts "foo" if r1[-1].andand.length == 2
=> nil
pry(main)> puts "foo" if r2[-1].andand.length == 2
=> nil
pry(main)> puts "foo" if r3[-1].andand.length == 2
foo
=> nil
Upvotes: 2
Reputation: 84114
In ruby the not
operator has lower precedence than &&
so your code is being interpreted as
not (results.empty? && (results[-1].length == 2))
You probably want to use the ! operator instead which does the same as not
but has higher precedence.
Upvotes: 1