Skip to content

Instantly share code, notes, and snippets.

@naohaq
Created June 22, 2012 08:15
Show Gist options
  • Save naohaq/2971266 to your computer and use it in GitHub Desktop.
Save naohaq/2971266 to your computer and use it in GitHub Desktop.
Scoping of local variables in Ruby
colinux> ruby local.rb
foo(true):
a is not defined.
a is defined.
a = 1
foo(false):
a is not defined.
a is defined.
a = nil
#!/usr/bin/ruby1.9.1 -Ku
# -*- mode: ruby; coding: utf-8-unix -*-
def foo(t)
printf "foo(%s):\n", t.inspect
if defined?(a) then
printf " a is defined.\n"
else
printf " a is not defined.\n"
end
if t then
a = 1
end
if defined?(a) then
printf " a is defined.\n"
else
printf " a is not defined.\n"
end
printf " a = %s\n", a.inspect
printf "\n"
end
foo(true)
foo(false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment