Variable scoping

Hi All,

Recently I found a slightly annoying behavior in Ruby -- local variable
scoping: Example of code:

Javascript version:

var aNumber = 3
function doSomething()
{
   var anotherNumber = aNumber *2
}

Translate to Ruby:

aNumber = 3
def doSomething
    anotherNumber = aNumber * 2
end

This does not work because aNumber is defined outside of the function.
In most other languages, a variable defined in the "parent" name space
of a function will be visible to the function. This is not the case in
Ruby. Now my question is, how can I do this in the Ruby Way:

def min(*params)
  _min = nil
  params.each do |p|
    next if p.nil?
    if _min.nil? or eval(p) < eval(_min) then
      _min = p
    end
  end
  return _min
end
a = 1
b = 2
c = 3
d = 4
puts min("a", "b", "c", "d")

Purpose of this function is to get the NAME of the variable that has
minimum value.

Thank you!

Shannon

Xiangrong Fang wrote:
...

In most other languages, a variable defined in the "parent" name space
of a function will be visible to the function. This is not the case in
Ruby. Now my question is, how can I do this in the Ruby Way:

def min(*params)
  _min = nil
  params.each do |p|
    next if p.nil?
    if _min.nil? or eval(p) < eval(_min) then
      _min = p
    end
  end
  return _min
end
a = 1
b = 2
c = 3
d = 4
puts min("a", "b", "c", "d")

Purpose of this function is to get the NAME of the variable that has
minimum value.

It's possible:

a=b=c=d=nil

(class << self; self; end).send :define_method, :min do |*params|
   _min = nil
   params.each do |p|
     next if p.nil?
     if _min.nil? or eval(p) < eval(_min) then
       _min = p
     end
   end
   return _min
end

a = 1
b = 2
c = 3
d = 4
puts min("a", "b", "c", "d")

But why are you interested in the name of a variable?