17
  # Get our data back
  def queryNewsTable
    @conn.exec( "SELECT * FROM newslib" ) do |result|
      result.each do |row|
        yield row if block_given?
      end
    end
  end

For this piece of code. I don't quite understand yield row if block_given?

can anybody point to any good article teaching about this or you can briefly explain it to me a little bit thanks so much

BufBills
  • 8,005
  • 12
  • 48
  • 90
  • it's usually good style to provide what happens when a block *isn't* given, as well.. i.e. provide `result.to_enum` – roippi Feb 09 '14 at 04:22

3 Answers3

8

This yield row if block_given? means that block which could be passed into the #queryNewsTable method(!), is evaluated with operator, in other words, if you pass the block into function #queryNewsTable:

queryNewsTable do 
   #some code
end

You will get the call to the code, for each of rows in the result variable.

NOTE: That for your case it will be better to optimize the code (if not is used):

# Get our data back
def queryNewsTable
  @conn.exec( "SELECT * FROM newslib" ) do |result|
    result.each do |row|
      yield row
    end
  end if block_given?
end   
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
5

Ask yourself how Hash.new works:

http://www.ruby-doc.org/core-2.1.0/Hash.html#method-c-new

It can take no argument, a single argument, or a block. If there is no argument, fetching the value for a non-existent key gives nil. If there is a block, fetching the value for a non-existent key gives whatever the block says to give. Clearly its implementation needs a way to ask "was there a block?" so that it knows which behavior to use. That is what block_given? does.

http://www.ruby-doc.org/core-2.1.0/Kernel.html#method-i-block_given-3F

As for yield, it is simply the way a method that has taken a block calls the block, passing it parameters as needed.

matt
  • 515,959
  • 87
  • 875
  • 1,141
2

When you use functions like Enumerable#each, you typically pass in a block using {|arg| ... } or do ... end. The line yield row if block_given? checks to see if a block was supplied to this function call, and if it was, calls that block with row as an argument.

One way you might use this function would be:

queryNewsTable {|row| puts row}

This example would print each row of the query to standard output, since the block that does the printing gets called for each row in the query result. If no block were given, then that line would be ignored.

derekerdmann
  • 17,696
  • 11
  • 76
  • 110