Search code examples
rubykoan

File.open with block vs without


I have a question about Block, do the two codes mean the same?

code 1

File::open('yozloy.txt','w') do |f|
  f << 'Some contains'
end

code 2

newFile = File::open('yozloy.txt','w')
newFile << 'Some contains'

Solution

  • DarkDust already said that these methods are different. I'll explain you the blocks a little more, as I suppose that I can guess why you asked this question ;-)

    The block in ruby is just a parameter for some method. It's not just a different syntax.

    Methods which accept (optional) blocks usually have a condition to test whether they have been called with block, or without.

    Consider this very simplified example: (the real File.open is similar, but it ensures the file is closed even if your block raises an error, for example)

    def open(fname)
      self.do_open(fname)
      if block_given?
        yield(self) # This will 'run' the block with given parameter
        self.close
      else
        return self # This will just return some value
      end
    end
    

    In general, every method may work (works) differently with a block or without a block. It should be always stated in the method documentation.