Hi all,
Below is my code
h={}
arr=[]
def gethash
h[1]=0
return h
end
arr[0]=gethash
puts arr[0].each {|k,v| puts “key #{k} value #{v}”}
For the above i get error saying “Undifined local variable or method ‘h’
for main:Object(NameError)”
may i know reason for this error?
Hi –
On Sun, 18 Apr 2010, Simbolla S. wrote:
arr[0]=gethash
puts arr[0].each {|k,v| puts “key #{k} value #{v}”}
For the above i get error saying “Undifined local variable or method ‘h’
for main:Object(NameError)”
may i know reason for this error?
The def keyword starts a new local scope. The same happens with class:
a = 1
class C
puts a # new local scope, so a is not defined
end
David
–
David A. Black, Senior Developer, Cyrus Innovation Inc.
THE Ruby training with Black/Brown/McAnally
COMPLEAT Coming to Chicago area, June 18-19, 2010!
RUBYIST http://www.compleatrubyist.com
On Sat, Apr 17, 2010 at 7:30 PM, Simbolla S. [email protected]
wrote:
arr[0]=gethash
puts arr[0].each {|k,v| puts “key #{k} value #{v}”}
to my dismay
def xxx… end
is not a closure
while
define_method :xxx is
IOW
h is just not visible in def while it would if you define gethas via
define_method
be careful though on the toplevel you cannot use define_method, do
something like
include( Module::new do
h = {}
define_method :xxx do h.tap{ |hh| h[1] = 0 } end
end )
puts xxx
xxx[:a] = 42
puts xxx
oh yes this code is ugly, but I wanted to demonstrate the semantics…
HTH
R.
On Apr 17, 11:30 am, Simbolla S. [email protected] wrote:
for main:Object(NameError)"
If you want h to be a global variable, accessible everywhere, prefix
it with a dollar sign:
$h={}
def foo
$h[1]=0
$h
end
foo
p $h
#=> {1=>0}
Gavin K. wrote:
On Apr 17, 11:30�am, Simbolla S. [email protected] wrote:
for main:Object(NameError)"
If you want h to be a global variable, accessible everywhere, prefix
it with a dollar sign:
$h={}
def foo
$h[1]=0
$h
end
foo
p $h
#=> {1=>0}
But usually it would be better instead to:
(1) pass h as an argument to method foo; or
(2) define a class with instance variable @h