class Array
def inject(n)
each { |value| n = yield(n, value) }
n
end
def sum
inject(0) { |n, value| n + value }
end
end
[ 1, 2, 3, 4, 5 ].sum >> 15
sum passes 0 to inject.
inject iterates through all items in the array (array.each), placing the
current array element's value in value
For each value in the array, n is set to the return value of the calling
block.
Where the calling block is "n + value" in sum.
It may help to think of the block as if it were "return n + value".
yield calls sum's block with the current values of n and value. (n,
value) ---> |n, value|
inject returns the final value of n.
Here's a better explanation:
http://errtheblog.com/post/633
James
db 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
>>>>
>
>
> >
>
>
>
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---