From: "Daniel Schüle" Date: 2006-01-04T08:52:58+09:00 Subject: block and method local variables hello all, consider follow code irb(main):528:0* def abc irb(main):529:1> ppp=111 irb(main):530:1> puts ppp irb(main):531:1> yield irb(main):532:1> puts ppp irb(main):533:1> ppp irb(main):534:1> end => nil irb(main):536:0> abc {} 111 111 => 111 irb(main):537:0> abc { puts ppp } 111 NameError: undefined local variable or method `ppp' for main:Object from (irb):537 from (irb):537:in `abc' from (irb):537 from :0 irb(main):538:0> irb(main):539:0* irb(main):540:0* ppp = "OOO" => "OOO" irb(main):541:0> abc { puts ppp } 111 OOO 111 => 111 irb(main):542:0> I am right assuming that all "local" variables in the method abc are invisible in the block? I tried a little more irb(main):544:0* def cba irb(main):545:1> ppp = 222 irb(main):546:1> puts ppp irb(main):547:1> yield ppp irb(main):548:1> puts ppp irb(main):549:1> ppp irb(main):550:1> end => nil irb(main):551:0> cba {} 222 222 => 222 irb(main):552:0> cba {|p|} 222 222 => 222 irb(main):553:0> cba {|p| p = 333} 222 222 => 222 irb(main):554:0> cba {|p| puts p; p = 333} 222 222 222 => 222 irb(main):555:0> if explicitely passed to block ppp is now visible there. but seems to be imposible to change the "method local" variable ppp in this case. the following *does* work irb(main):557:0* def xxx irb(main):558:1> ppp = [1] irb(main):559:1> p ppp irb(main):560:1> yield ppp irb(main):561:1> p ppp irb(main):562:1> ppp irb(main):563:1> end => nil irb(main):564:0> xxx {} [1] [1] => [1] irb(main):565:0> xxx {|x| } [1] [1] => [1] irb(main):566:0> xxx {|x| x[0]=2 } [1] [2] => [2] irb(main):567:0> and I kind of understand why it works if I change line 566 to irb(main):566:0> xxx {|x| x=[2] } than it would not work the reason I came accross this is following I was reading " Parameters to a block may be existing local variables; if so, the new value of the variable will be retained after the block completes. This may lead to unexpected behavior, but there is also a performance gain to be had by using variables that already exist " and in my understanding all variables defined in a method are "local" (C++ background) If not local what are they considered to be then? Regards, Daniel