A problem to think ‘block’ in Ruby

I was searching for a good explanation for a block concept in Ruby. I understand how it works but still feel that to write a code with blocks is unnatural. It is not natural to how human thinks or at least how I think. I am familiar with a for loop style which is a more straight forward way of thinking.

For example, I’m going to find a sum of numbers in an array. In paper, I might be able to do it in my head. But how I do it? I would find a pair that are easy to find a sum, for example, 1 and 9. Basically each time I do a sum of two numbers. But computer can’t do the same thing, it does things in sequence, either from start to end or reversely. Of course, I’m sure we can program so the computer can simulate the thinking process as I do but it just makes it more complex to solve a simple problem. And that’s way I think to write a code in Java using a for loop is more intuitive. So in Java, I can have a sum variable then iterate over the array to sum each element and assign the result to the sum variable. But in Ruby, I found an example as shown below

class Array
def inject( n )
each { |value| n = yield( n, value ) }
def sum( n )
inject( 0 ) { |n, value| n + value }

>> |1, 2, 3, 4, 5|.sum          # sum = 15

I still don’t see the logic how to think to be able to write the code above. It’s easy to understand when reading the code but if I want to create one how can I do it? The code above, to me, has two delegations. Do we do the same kind of delegation when we solve the sum problem in our head?

Will I be able to solve programming problems with blocks, I mean to write code naturally? Is this just a matter of learning a new concept in a new language? Is it just a matter of practicing the language and its structure, the same as when I study Swedish?


Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: