Undifined local variable or method error

S

Simbolla Simbolla

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?
 
R

Robert Dober

Hi all,

Below is my code

=A0h=3D{}
=A0arr=3D[]
def gethash
=A0h[1]=3D0
=A0return h
end
arr[0]=3Dgethash
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 =3D {}
define_method :xxx do h.tap{ |hh| h[1] =3D 0 } end
end )

puts xxx
xxx[:a] =3D 42
puts xxx

oh yes this code is ugly, but I wanted to demonstrate the semantics...
HTH
R.


--=20
The best way to predict the future is to invent it.
-- Alan Kay
 
D

David A. Black

Hi --

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?

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
 
P

Phrogz

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)"

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}
 
B

Brian Candler

Gavin said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,054
Members
48,769
Latest member
Clifft

Latest Threads

Top