Ruby Blocks and Blocks
I’m reading Programming Ruby: 2nd Ed. and an example on page 57 has captured my attention. (Code slightly modified for brevity)
"3 4\n5 6\n7 8".each do |line| v1, v2 = line.split print Integer(v1) + Integer(v2), " " end
The book is just explaining to Perl coders that you have to call Integer() to convert strings to ints, but I see an interesting opportunity to restructure the code.
"3 4\n5 6\n7 8".collect do |line| line.split end.each do |a, b| print Integer(a) + Integer(b), " " end
My brain is nagging me that there’s a fundamental concept at work in this change, but I can’t quite put my finger on it. It’s not just that I’m building an array in the middle or that it evaluates differently (after producing identical output), it’s that it looks something like nested fuction calls. It feels like a more a functional style of programming, but that’s not quite all.
I’m compelled to write this as a block yielding to a block, though it doesn’t compile:
"3 4\n5 6\n7 8".collect { |line| yield line.split } { |a, b| print Integer(a) + Integer(b), " " }
Any thoughts? Am I just being weird, or can anyone put better words to it?
Want more? I'm not as good at forgetting to update @pushcx on Twitter.
Conversation (6)
Jump to comment form | comments rss [?]Add this link to your feed reader to watch for new replies to this post. | trackback uri [?]Trackback this link in a blog post to create a comment here linking to your post.