scope limitation causes problems for me.

±

±èÁØ¿µ

[Note: parts of this message were removed to make it a legal post.]

hi, everyone.

I have the following codes.

m = Hash.new("merong")

m["b"] = "babo"

def func
begin
m["a"] = "merong"
rescue => e
puts e
end
end

func



exception is

undefined local variable or method `m' for main:Object

Could I know the reason this was caused??
 
P

Peter Hickman

[Note: parts of this message were removed to make it a legal post.]

You either need to pass m as a parameter

def func(m)
begin
m["a"] = "merong"
rescue => e
puts e
end
end

and call it like

func(m)

or make m global

$m = Hash.new("merong")

$m["b"] = "babo"

def func
begin
$m["a"] = "merong"
rescue => e
puts e
end
end

func

I recommend the first way
 
J

Jesús Gabriel y Galán

hi, everyone.

I have the following codes.

m =3D Hash.new("merong")

m["b"] =3D "babo"

def func
=C2=A0 =C2=A0begin
=C2=A0 =C2=A0 =C2=A0 =C2=A0m["a"] =3D "merong"
=C2=A0 =C2=A0rescue =3D> e
=C2=A0 =C2=A0 =C2=A0 =C2=A0puts e
=C2=A0 =C2=A0end
end

func



exception is

undefined local variable or method `m' for main:Object

Could I know the reason this was caused??

The reason is that the def keyword starts a new scope, and doesn't
inherit the surrounding scope (it's not a closure). You could pass the
hash as a parameter to the function for example:

m =3D Hash.new("merong")
m["b"] =3D "babo"

def func hash
begin
hash["a"] =3D "merong"
rescue =3D> e
puts e
end
end

func m

Or use define_method, if you really wanted a closure over that scope:


m =3D Hash.new("merong")
m["b"] =3D "babo"

self.class.send :)define_method, :func) do
begin
m["a"] =3D "merong"
rescue =3D> e
puts e
end
end

func

Jesus.
 

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

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top