From: Robert Klemme Date: 2007-05-29T21:25:16+09:00 Subject: Re: Underscore On 29.05.2007 14:11, Robert Klemme wrote: > On 29.05.2007 13:59, Chris Carter wrote: >> On 5/29/07, Robert Klemme wrote: >>> On 29.05.2007 13:07, Jano Svitok wrote: >>> > On 5/29/07, Jon Harrop wrote: >>> >> Michael Fellinger wrote: >>> >> > some people use _ as a temporary meaningless variable, just a >>> >> > throw-away so to say. >>> >> > In this case something like >>> >> > >>> >> > hash = {:a => :b, :c => :d} >>> >> > >>> >> > and you are not interested in the :b and :d >>> >> > >>> >> > hash.each do |key, _| >>> >> > p key >>> >> > end >>> >> > >>> >> > I'm not necessarily a friend of this technique, but it seems >>> easy on >>> >> > the minds of some people. >>> >> >>> >> Right, this is exactly what I guessed it was doing (it is the same in >>> >> SML/OCaml/F#) but what value was being thrown away in the Ruby >>> program >>> >> and >>> >> where did it come from? >>> >> >>> >> (1..n).inject(x) { |acc, _| yield(acc) } >>> >> >>> >> -- >>> >> Dr Jon D Harrop, Flying Frog Consultancy >>> >> The F#.NET Journal >>> >> http://www.ffconsultancy.com/products/fsharp_journal/?usenet >>> > >>> > inject takes a block with two parameters. classic example is a sum >>> of an >>> > array: >>> > >>> > array.inject(0) {|sum, item| sum + item } >>> > >>> > so, in this case, item is not needed, so it is replaced by a variable >>> > with name of "_" >>> > that by convention means "temporary", "throw away" >>> > >>> > it can be anything else: >>> > (1..n).inject(x) { |acc, i_dont_need_this| yield(acc) } >>> >>> Actually, #inject does not really make sense in this case. All that >>> happens here is that some value is yielded n times to a block. That >>> could have been done much more concise like this: >>> >>> n.times { yield x } >>> >>> Kind regards >>> >>> robert >>> >>> >> >> Actually, If it does what I think it does, the inject is needed >> because as we know, inject sets the value returned from the block as >> the accumulator for the next round. Therefore: >>>> nest(2) {|x| p x; [22] } >> 2 >> [22] >> => [22] > > Stupid me. Of course you are right. I should have taken more time to > digest this - or have more coffee. Thank you for correcting me! I was too fast (again). Even though the return value is used, I'd rather do n.times { x = yield x } than using #inject which does more than needed in this case. :-) Now, did I look at all aspects...? Kind regards robert