From: Bill Guindon Date: 2007-05-25T07:59:44+09:00 Subject: Re: Introducing the "it" keyword On 5/24/07, dblack@wobblini.net wrote: > Hi -- > > On Fri, 25 May 2007, Greg Fodor wrote: > > > A common pattern seen in a lot of ruby code is: > > > > g(m(x)) if/unless/while/until h(m(x)) > > > > for example, > > > > puts "User: #{opts[:user]}" if opts[:user] > > in this case, g(x) = puts "User: #{x}", h(x) = x, and m(x) = > > opts[:user] > > > > or > > > > return v+1 if v +1 < 10 > > In this case, g(x) = x, h(x) = x < 10, and m(x) = v + 1 > > > > This is obviously suboptimal code, as is, because it results in the > > evaluation of m(x) twice. I propose a new keyword is added, "it", > > which may appear within the statement to the left of the decorator. > > So, the previous statements become: > > > > puts "User: #{it}" if opts[:user] > > > > and > > > > return it if |v + 1| < 10 > > > > If and only if "it" is seen on the left hand side, the ruby > > interpreter should store the expression result on the conditional into > > a temporary storage and evaluate that as "it". It falls out of scope > > after the statement. The use of pipes can designate a subexpression to > > use for "it" instead (I don't have my heart set on pipes, but you get > > the idea.) > > > > This keyword allows better DRY in ruby for this g(m(x)) op h(m(x)) > > pattern and also provides a nice optimization since your average lazy > > programmer will usually evaluate m(x) twice instead of putting it into > > temporary local storage themselves. By promoting it to a keyword, you > > also prevent the problems seen here: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/166828 > > > > Thoughts? > > I think something like 99% of all suggestions for changes to Ruby > involve new punctuation -- which means that only a very tiny number of > them can be accepted before Ruby turns into complete line noise. So > I'd not advocate the pipes version. Maybe you could do: > > return v + 1 if its < 10 > > which of course is missing an apostrophe, speaking of punctuation :-) > But something like that, maybe. > Well, you fixed the thing that was bothering me. In the original proposal, 'it' appeared too early, leaving me wonder what 'it' was. It makes sense for 'it' to follow what 'it' is referring to. You could solve the apostrophe problem with the longer 'it_is'. Overall, I like the idea. It solves the lazy programmer problem which leads to double evaluation of the same expression Those who take the effort to assign it to a temp variable, can now be lazy, and do it with one line. > David > > -- > Q. What is THE Ruby book for Rails developers? > A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) > (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) > Q. Where can I get Ruby/Rails on-site training, consulting, coaching? > A. Ruby Power and Light, LLC (http://www.rubypal.com) > > -- Bill Guindon (aka aGorilla) The best answer to most questions is "it depends".