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?
Disclaimer: I'm not a python expert
python, , , . Ruby, , . , , procs/lambdas, , .
Ruby :
ALL_CAPS
@@double_at
@single_at
get_instance_variable
$starts_with_dollar
Ruby, , , , . Ruby , , , .
$.
$
$a = 5 def myfunc puts $a end myfunc
, , .
dis, , Python.
dis
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 .
a