Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Really brief explanation of why Ruby's blocks are awesome
Index -> Programming, Ruby -> Ruby Tutorials
Goto page Previous  1, 2
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Insectoid




PostPosted: Mon Nov 02, 2009 9:03 pm   Post subject: RE:Really brief explanation of why Ruby\'s blocks are awesome

I see, so 'true' is 'a' the first time the block is run. 'a&&b' would be 'a' the next time. So this iterates recursively then?
Sponsor
Sponsor
Sponsor
sponsor
DtY




PostPosted: Mon Nov 02, 2009 9:07 pm   Post subject: RE:Really brief explanation of why Ruby\'s blocks are awesome

Kinda recursively, say you do:

[A,B,C].inject(true){|a,b| a && b}
It would evaluate to
( (true && A) && B) && C ) )
This might help: http://ruby-doc.org/core/classes/Enumerable.html#M003140
wtd




PostPosted: Tue Nov 03, 2009 11:54 am   Post subject: Re: RE:Really brief explanation of why Ruby\'s blocks are awesome

insectoid @ Tue Nov 03, 2009 10:03 am wrote:
I see, so 'true' is 'a' the first time the block is run. 'a&&b' would be 'a' the next time. So this iterates recursively then?


I doubt this is implemented recursively, but it is a gateway drug to functional programming, where it would be done recursively.

code:
let rec inject f init v =
    match v with
        [] -> init
      | x::xs -> inject f (f init x) xs
in
    inject (fun a b -> a + b) 0 [3; 4; 5]
apomb




PostPosted: Tue Nov 03, 2009 12:16 pm   Post subject: RE:Really brief explanation of why Ruby\'s blocks are awesome

Thanks DtY, that actually helped alot in understanding enums and blocks.
Insectoid




PostPosted: Tue Nov 03, 2009 5:05 pm   Post subject: RE:Really brief explanation of why Ruby\'s blocks are awesome

Yeah, I realized that while walking to school today. While recursion would take the problem and work backwards, to find the smallest problem which it CAN solve, this is already at the beginning.
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 2 of 2  [ 20 Posts ]
Goto page Previous  1, 2
Jump to:   


Style:  
Search: