Syed Aslam
Syed Aslam

Reputation: 8807

Why does this code snippet output "true" when it should return "false"?

ALLOWED_TARGETS = ["dresden", "paris", "vienna"]

def missile_launch_allowed(target, secret_key)
  allowed = true
  аllowed = false if secret_key != 1234
  allowed = false unless ALLOWED_TARGETS.include?(target)
  allowed
end

puts(missile_launch_allowed("dresden", 9999))

Found this code snippet in a blog. Tracking the code by hand gives me false, but why does this output true when run?

The part I am not seeing is just not crossing my mind at the moment. Please help me understand Ruby a bit better.

Upvotes: 4

Views: 103

Answers (1)

Amadan
Amadan

Reputation: 198294

allowed is not аllowed; you have two different variables. Specifically, the first letter is different: the first variable has 'LATIN SMALL LETTER A' (U+0061), the second has 'CYRILLIC SMALL LETTER A' (U+0430). The glyphs are either similar or identical in most (all?) fonts. Your code is thus equivalent to:

ALLOWED_TARGETS = ["dresden", "paris", "vienna"]

def missile_launch_allowed(target, secret_key)
  first = true
  second = false if secret_key != 1234
  first = false unless ALLOWED_TARGETS.include?(target)
  first
end

puts(missile_launch_allowed("dresden", 9999))

With variables renamed somewhat more sensibly, it should be obvious why you are getting the result you are.

Upvotes: 8

Related Questions