From: Robert Klemme Date: 2008-09-01T20:25:09+09:00 Subject: Re: Request for Block local methods, and Proc syntax 2008/9/1 Patrick Li : > So after using Ruby for a little over two months, I've made the complete > switch from Java to Ruby and I'm loving it. > > But I have two features that I would like to add to Ruby if possible. > Would you guys be able to tell me if these features are > consistent/possible? > > 1) Block local methods: > > def myMethod > def myLocalMethod #<-- myLocalMethod only visible within myMethod() > end > end > > This doesn't look like much at first. But it's extremely useful for > meta-programming. Right now, people are using instance_eval to get > around this, which creates some scoping problems. > > we can do stuff like this: > > def html(&block) > block.instance_eval do > def image > end > end > end > > which we can use like this: > > html do > image() > end This does not really make sense. block.instance_eval evaluates the block with self set to "block". But inside the block where you invoke image() self is assigned to what it was before invocation of method html. To achieve what you want you do not need a new feature in Ruby: irb(main):001:0> def html(&block) irb(main):002:1> context = Object.new irb(main):003:1> def context.image irb(main):004:2> puts "An image" irb(main):005:2> end irb(main):006:1> context.instance_eval &block irb(main):007:1> end => nil irb(main):008:0> html do irb(main):009:1* puts "intro" irb(main):010:1> image irb(main):011:1> puts "extro" irb(main):012:1> end intro An image extro => nil irb(main):013:0> > 2) Procs without proc keyword. > > Is there any reason why we need a proc keyword in front of a block? To disambiguate an empty Hash from an empty block. > Wouldn't it be cleaner if every do/end or {} created a block? Then most > language constructs can be user-defined: > > for example we can write this: > > while {x} do > puts "a" > end > > where "while" is just a method that takes two block arguments. You can simply work around this by doing something like def l(&b) b end Then you can do "l{x}" > We can even write our own object system: > > klass MyKlass do > defMethod :ourMethod do > puts "cool huh?" > end > end What exactly is this supposed to do? Where does creating a block without "proc" or "lambda" play a role here? Please, do not easily jump to asking for language changes. Most of the time it turns out that things are the way they are for a reason and usually there is a solution that does not involve changing the language. Cheers robert -- use.inject do |as, often| as.you_can - without end