[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Variable scoping

Joel VanderWerf

3/20/2005 5:57:00 AM

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?