I do, but its confusing because everything is called n and value, does
this make it clearer:
class Array
def inject(inn)
self.each { |evalue| inn = yield(inn, evalue) }
return inn
end
def sum
inject(0) { |sn, svalue| sn + svalue }
end
def product
inject(1) { |pn, pvalue| pn * pvalue }
end
end
I'm not exactly sure of your question, do you mean the array elements?
if so, that would happen with this line 'each { |evalue| inn =
yield(inn, evalue) }'
Brian
On 6/15/07, db <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> I am getting into Ruby. I've only written one program so far, after a
> week of letting
> the main chapters of 'Programming Ruby' sink in.
>
> It takes a dir of "Artist - title.mp3"s and move them to new folders
> called "Artist"
> Only about 7 lines of code. So it's a decent scripting language.
>
> But the things Gopal mentioned are what are exciting about it,
> as mix-in's and functional programming need to be coded
> in Java as decorators and visitors design patterns.
>
> Dan
>
> PS.
> I am having trouble understanding the syntax of 'inject'.
> Does anyone understand how variables get set here?:
>
> class Array
> def inject(n)
> each { |value| n = yield(n, value) }
> n
> end
> def sum
> inject(0) { |n, value| n + value }
> end
> def product
> inject(1) { |n, value| n * value }
> end
> end
> [ 1, 2, 3, 4, 5 ].sum >> 15
> [ 1, 2, 3, 4, 5 ].product >> 120
>
>
>
>
> > >> Hi all
> >
> > >> Anybody using ruby out there?
> >
> > >> Brian
> >
> > >> --
> > >> Brian Silberbauer
> > >> Consultant
> >
> > >> +27 (0)83 566 2705
> > >> skype: brian.silberbauer
> >
> > >> --
> > >> No virus found in this incoming message.
> > >> Checked by AVG Free Edition.
> > >> Version: 7.5.472 / Virus Database: 269.8.15/848 - Release Date: 6/13/2007
> > >> 12:50 PM
>
>
> >
>
--
Brian Silberbauer
Consultant
+27 (0)83 566 2705
skype: brian.silberbauer
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"CTJUG Forum" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/CTJUG-Forum
For the ctjug home page see http://www.ctjug.org.za
-~----------~----~----~----~------~----~------~--~---