From: Mike Gold Date: 2008-11-01T04:20:12+09:00 Subject: Re: How to access to local variables in enclosing scopes? Yuh-Ruey Chen wrote: > >> � �MyClass.class_eval do >> � � �define_method(m) { puts "Hi from #{m}!" } >> � �end >> >> and similar. > > Yes I'm familiar with them, and I actually would like to use them, but > blocks can't have default arguments. Ideally, I would like to write > everything with blocks and avoid all this magical "new scope" > nonsense. It makes metaprogramming tricky in my experience. I use often use Class.new and define_method for just the reasons you describe: metaprogramming most naturally goes with locals bound to closures. This style also avoids a handful of potential problems with the "regular" way of using different scopes, in particular name conflicts and lack of true read-only protection for variables. I was told that I wasn't doing things in a "rubyish" way. Disregard that BS. Use closures and define_method for metaprogramming. Your code will be better. Note 1.9 allows default arguments for lambdas as well as a &block parameter. 1.8.7 allows a &block parameter where 1.8.6 does not. For 1.8.x you can get the same effect of default arguments like this class << self define_method(:foo) { |*args| a, b = case args.size when 0 ["fred", "barney"] when 1 [args.first, "barney"] when 2 args else raise ArgumentError, "wrong number of arguments (#{args.size} for 2)" end puts "foo: #{a} #{b}" } end foo #=> foo: fred barney foo :a #=> foo: a barney foo :a, :b #=> foo: a b -- Posted via http://www.ruby-forum.com/.