On Thu, 2006-03-02 at 00:50 +0900, Edward Faulkner wrote:
> On Thu, Mar 02, 2006 at 12:14:47AM +0900, Adam Groves wrote:
> > But I'm stuck here.
> > 
> >   (1...n).inject("A") { |curr, i| curr.succ}
> > 
> > I still can't quite get my head around blocks beyond .each do |x|
> 
> #inject is one of the basic tools of functional programming.  That's
> why it seems hard.  It's a very different way of thinking.  And also
> very powerful.
> 
> That said, I think this case is a completely gratuitious use of
> inject.  The tipoff is that the argument "i" is completely ignored.
> 

Well, sorry, I didn't realise we had to use them all. I like to use it
where I want to give back something new from a block, but don't want:

	a = []
	something.each { |e| a << e end }
	a

In this case it was just a snazzier alternative to doing the (n-1).times
and so on...

Did I say I'm an #inject *addict* ?

> I like this much better:
> 
> def letter(n)
>   return '_' if n==0
>   n==1 ? "A" : letter(n-1).succ
> end
> 

Well, to each his own, but (maybe this is a bit pathological,
though...):

	def letter(n)
	  (1...n).inject("A") { |curr, i| curr.succ}
	end

	def letter2(n)
	  return '_' if n==0
	  n==1 ? "A" : letter2(n-1).succ
	end

	p letter(327021)
	# => "ROSS"

	p letter2(327021)
	# => -:3:in `letter2': stack level too deep (SystemStackError)
                    from -:3:in `letter2'
	            from -:11

-- 
Ross Bamford - rosco / roscopeco.REMOVE.co.uk