Luigi Palermo
Luigi Palermo

Reputation: 33

How the comparison operator '==' work with the 'if' statement of the code below?

As shown in the below method, I do not understand how the 'comparison operator' works. If the defined 'stack array' is initially empty how can the elements of the hash 'OPPOSITE' can be compared with the last element of an empty array? Does the comparison happen on the operand 'OPPOSITE[dir]'? Even if so, it is still not clear.

Thanks

code:

 OPPOSITE = {
   "NORTH" => "SOUTH",
   "SOUTH" => "NORTH",
   "EAST"  => "WEST",
   "WEST"  => "EAST"
 }

def dirReduc(arr)
  stack = []

  arr.each do |dir|
    OPPOSITE[dir] == stack.last ? stack.pop : stack.push(dir)
  end

  stack
end 


 arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]

 print dirReduc(arr)

Upvotes: 0

Views: 47

Answers (1)

spickermann
spickermann

Reputation: 106782

When the stack is empty then stack.last will return nil.

OPPOSITE['NORHT'] will return 'SOUTH' and 'SOUTH' == nil if false, therefore the else branch (stack.push(dir)) will be evaluated.

Upvotes: 2

Related Questions