Search code examples
ruby-on-railsblock

Basic Ruby/Rails question about understanding blocks & block variables


I'm starting to get comfortable with Ruby/Rails but must admit I still look askance when I see an unfamiliar block. take the following code:

(5..10).reduce(0) do |sum, value|
  sum + value
end

I know what it does...but, how does one know the order of the parameters passed into a block in Ruby? Are they taken in order? How do you quickly know what they represent?

I'm assuming one must look at the source (or documentation) to uncover what's being yielded...but is there a shortcut? I guess I'm wondering how the old vets quickly discern what a block is doing?!? How should one approach looking at/interpreting blocks?


Solution

  • When you write code, there's no other way than checking the documentation - even if Ruby is quite consistent and coherent in this kind of things, so often you just expect things to work on a particular way. On the other hand, when you read code, you can just hope that the coder has been smart and kind enough to use consistent variable names. In your example

    (5..10).reduce(0) do |sum, value|
      sum + value
    end
    

    There is a reason if the variables are called sum and value! :-) Something like

    (5..10).reduce(0) {|i,j|i+j}
    

    is of course the same, but much less readable. So the lesson here is: write good code and you'll convey some piece of information more than just instructions to a computer!