0

Very new to ruby. I'm trying to see if I can write html using ruby. Very basic script. No errors but nothing is written to the file and I can't figure out why. If I use puts after mypage I can see the html written to the console

    #!/usr/bin/env ruby

class MyPage
  attr_accessor :para, :startbuff


      def initialize

        @para = "<p>"
        @startbuff = "<!DOCTYPE HTML>

<html>

<head>
    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />
    <title>Your Website</title>
</head>

<body>

</body>

</html>"


      end

      def makePage
        puts @startbuff
      end

  end

    mypage = MyPage.new

    File.open("/Users/me/Desktop/MyRubyHTML.html", "w+").each { |file|  
      puts mypage.makePage
    }
Sebastian Zeki
  • 6,690
  • 11
  • 60
  • 125

2 Answers2

3

puts outputs to the console, you need to do this instead:

def makepage
  @startbuff
end

this returns whatever is in @startbuff and then:

File.open("/Users/me/Desktop/MyRubyHTML.html", "w+") { |file|  file.write(mypage.makepage) }
Amr Noman
  • 2,597
  • 13
  • 24
  • Actually the problem was the .each which I didn't need. Found this answer http://stackoverflow.com/questions/6833887/file-open-and-blocks-in-ruby-1-8-7 – Sebastian Zeki Jan 18 '16 at 16:42
1

Did you notice, that you never actually used your filehandle? No wonder, that nothing gets written to the file. Try

 file.puts(....)
user1934428
  • 19,864
  • 7
  • 42
  • 87