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

Sye*_*lam 4 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))
Run Code Online (Sandbox Code Playgroud)

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.

Ama*_*dan 8

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))
Run Code Online (Sandbox Code Playgroud)

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

  • 啊,我讨厌这些问题:) (4认同)
  • 合适的术语似乎是[homoglyph](https://en.wikipedia.org/wiki/Homoglyph) (3认同)
  • @SyedAslam _“您在编程语言面试中到底要对此类问题进行什么测试?” _ –您可能如何调试一个奇怪的问题?或看看您是否可以“跳出框框”。 (2认同)