Radek
Radek

Reputation: 11121

How the conditions are processed?

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

Answers (2)

Dave Newton
Dave Newton

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

Frederick Cheung
Frederick Cheung

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

Related Questions