Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope in Ruby and Python

Tags:

python

scope

ruby

I've been learning Ruby and Python concurrently and one of the things I noticed is that these 2 languages seem to treat scope differently. Here's 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 appears that def block can access variables declared outside of its immediate scope in Python but not in Ruby. Can someone confirm whether my understanding is correct? And if so, whether one of these ways of thinking of scope is more common in programming?

like image 602
wmock Avatar asked Feb 23 '13 16:02

wmock


1 Answers

Disclaimer: I'm no python expert

In python, where variables defined in a module are, by default, module variables and as such global to that module. In Ruby, when you define a lowercase variable, it is always a local variable. Local variables are only accessible in the block that defined them and in procs/lambdas defined in that block that wrap the variable.

In Ruby, for a variable to cross scopes, it needs to be either:

  • A constant (ALL_CAPS): Always accessible, if prefixed with the right scope
  • Class variable (@@double_at): Always accessible from the defining class and any subclasses, but not from outside
  • Instance variable (@single_at): Accessible only from within that object, and from outside with getter methods/get_instance_variable.
  • Global ($starts_with_dollar): A bad idea. Crosses all scopes, no scoping needed. Do not use!
like image 118
Linuxios Avatar answered Oct 25 '22 08:10

Linuxios