2

This question already has an answer Confusion with the assignment operation inside a falsy `if` block

  if false
      y = 'hi'
   end

  puts y

In ruby y has been "defined" in the if block,it will be nil(why?). Remove that block and this gives an error.

But, in python

 if False:
   y = 'hi'

 print y

It will gives an error.

What's happens in Ruby and Python?

Community
  • 1
  • 1
fcce
  • 1,034
  • 1
  • 12
  • 24
  • 1
    http://stackoverflow.com/questions/15042691/scope-in-ruby-and-python – iced May 05 '15 at 11:21
  • 1
    Not a duplicate, this has nothing to do with scope – steenslag May 05 '15 at 11:27
  • 1
    You have two questions here, so you should ask two questions. Actually, you shouldn't, because I know for a fact that the one about Ruby has already been asked and answered, and I strongly suspect that the same is true about the Python question as well. – Jörg W Mittag May 05 '15 at 11:29
  • Thx,I try to find the answers , but I can't find it.Can you post the url? – fcce May 05 '15 at 13:53
  • http://stackoverflow.com/questions/15183576/confusion-with-the-assignment-operation-inside-the-fallacy-if-block – fcce May 05 '15 at 14:27

1 Answers1

1

Yukihiro Matsumoto states

The local variables are created in compile time [...]

That's why y is defined in Ruby, whereas Python uses a dictionary to store local variables in runtime. This can be accessed directly through locals() as well.

The Ruby part also came up here.

Community
  • 1
  • 1
tynn
  • 38,113
  • 8
  • 108
  • 143
  • Python local variables are also recognized at compile time. The difference is that the name itself must actually be bound at run time, and in the question it is not. – chepner May 05 '15 at 12:08
  • @chepner [here](http://stackoverflow.com/questions/15183576/confusion-with-the-assignment-operation-inside-a-falsy-if-block) – fcce May 05 '15 at 14:33