Scope of Ruby and Python

I am learning Ruby and Python at the same time, and one of the things I noticed is that these 2 languages ​​seem to view the scope differently. Here is an example of what I mean:

# Python
a = 5
def myfunc():
  print a

myfunc() # => Successfully prints 5

# Ruby
a = 5
def myfunc
  puts a
end

myfunc # => Throws a "NameError: undefined local variable or method `a' for main:Object"

It looks like a def block can access variables declared outside its immediate scope in Python, but not in Ruby. Can anyone confirm the correctness of my understanding? And if so, is one of these scale thinking methods more common in programming?

+5
source share
3 answers

Disclaimer: I'm not a python expert

python, , , . Ruby, , . , , procs/lambdas, , .

Ruby :

  • (ALL_CAPS): ,
  • (@@double_at): ,
  • (@single_at): getter/ get_instance_variable.
  • ($starts_with_dollar): . , . !
+4

Ruby, , , , . Ruby , , , .

$.

$a = 5
def myfunc
  puts $a
end

myfunc

, , .

+1

dis, , Python.

import dis

a = 5
def myfunc():
  print a

:

>>> dis.dis(myfunc)
 15           0 LOAD_GLOBAL              0 (a)
              3 PRINT_ITEM          
              4 PRINT_NEWLINE       
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE

, , a .

+1

All Articles