r/learnruby • • Jul 13 '12

Trying to understand calling yield

I'm working through DAB's Well-Grounded Rubyist and am trying to figure out if I understand what is going on in an example he uses. Basically he writes a custom .each method using yield, and then uses that method in a custom .map method using yield as well.

To make sure I was understanding everything, I made my own version with different names/example situation and tried to annotate it to explain what was happening. I'm not sure if I got it right or not, and was looking for some feedback if possible.

My program Result

As a note, Ruby is my first programming language. I'm a grad student in Professional Writing and so my background has been HTML and CSS (no php).

1 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/andyhite Jul 13 '12

How about this, as a (somewhat contrived) example of using blocks:

class BottlesOfLiquid
  def initialize(number)
    @number = number
  end

  def sing(&block)
    @number.downto(1) do |i|
      puts block.call(i)
    end
  end
end

bottles = BottlesOfLiquid.new(99)
bottles.sing do |number|
  # The following should all be on one line...Reddit just jacked up the formatting since it was long
  "#{number} bottles of beer on the wall, #{number} of bottles of beer. Take one down, pass it around, 
   #{number - 1} bottles of beer on the wall"
end

A little silly, and probably not the best way to do it, but it's at least another use of blocks to wrap your head around!

1

u/vidus Jul 13 '12

Thanks, that does help. Still working on getting to .downto and other methods, but that looks very useful. Hoping to finish up Well-Grounded and move on to Eloquent Ruby in a week or two, so that should give me a bit better foundation too.