Ruby/Method/block given

Материал из Wiki.crossplatform.ru

Версия от 17:55, 13 сентября 2010; ViGOur (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

If there"s a block, pass in the file and close the file when it returns

  class File
    def File.my_open(*args)
      result = file = File.new(*args)
 
      if block_given?
        result = yield file
        file.close
      end
      return result
    end
  end



Is block ready

#!/usr/bin/env ruby
def gimme
  if block_given?
    yield
  else
    puts "Oops. No block."
  end
  puts "You"re welcome." # executes right after yield
end
gimme { print "Thank you. " } # => Thank you. You"re welcome.



The yield Statement using the block_given? method from Kernel.

# the job of yield is to execute the code block that is associated with the method. 
 
def gimme
  if block_given?
    yield
  else
    puts "I"m blockless!"
  end
end
gimme { print "Say hi to the people." } # => Say hi to the people.
gimme # => I"m blockless!