Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Scoping, Conditionals and Loops
Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Fri Oct 28, 2005 5:35 pm   Post subject: Scoping, Conditionals and Loops

Coming from something like C, C++, Java, C# or one of the other similar languages, Ruby's scoping rules may seem a bit odd.

Things like loops and conditionals don't introduce a new scope.

We might seem something like this in C:

code:
void foo()
{
   int bar;

   if (some_condition)
   {
      bar = 27;
   }
   else
   {
      bar = 42;
   }

   printf("%d\n", bar);
}


Rather than:

code:
void foo()
{
   if (some_condition)
   {
      int bar = 27;
   }
   else
   {
      int bar = 42;
   }

   printf("%d\n", bar);
}


Because in the latter bit of code, "bar" is local to each block. Once that conditional goes out of scope, those declarations go away. Thus the "printf" call fails.

code:
def foo
   if some_condition
      bar = 27
   else
      bar = 42
   end

   puts bar
end


Since there is no new scope introduced, bar sticks around.

This could be seen as good or bad, but at least it is the way things are, and understanding it is important for any Ruby programmer.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: