Prev: what is String#ord?
Next: Pagi something :(
From: Simbolla Simbolla on 17 Apr 2010 13:30 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? -- Posted via http://www.ruby-forum.com/.
From: David A. Black on 17 Apr 2010 14:26 Hi -- On Sun, 18 Apr 2010, Simbolla Simbolla wrote: > 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
From: Phrogz on 17 Apr 2010 21:53 On Apr 17, 11:30 am, Simbolla Simbolla <vinod...(a)gmail.com> wrote: > 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}
From: Brian Candler on 18 Apr 2010 04:59 Gavin Kistner wrote: > On Apr 17, 11:30�am, Simbolla Simbolla <vinod...(a)gmail.com> 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 -- Posted via http://www.ruby-forum.com/.
|
Pages: 1 Prev: what is String#ord? Next: Pagi something :( |