Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 719
Syed Aslam Avatar asked Jan 25 '23 16:01

Syed Aslam


1 Answers

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.

like image 76
Amadan Avatar answered Jan 29 '23 12:01

Amadan