how to print/write the result to a file

Discussion in 'Ruby' started by Li Chen, Oct 20, 2006.

  1. Li Chen

    Li Chen Guest

    Hi folks,

    Assume I have an array=[1,2,3]

    How do I print/write the result to a file called test.text either in the
    same folder or in a different folder?

    Thanks in advance,

    Li

    --
    Posted via http://www.ruby-forum.com/.
     
    Li Chen, Oct 20, 2006
    #1
    1. Advertising

  2. Li Chen

    Jan Svitok Guest

    On 10/20/06, Li Chen <> wrote:
    > Hi folks,
    >
    > Assume I have an array=[1,2,3]
    >
    > How do I print/write the result to a file called test.text either in the
    > same folder or in a different folder?
    >
    > Thanks in advance,
    >
    > Li


    It depends on the format you want, e.g.

    File.open('path/to/test.txt', 'w') do |f|
    f.write(array.join(', '))
    end

    1. you can use forward slashes (/) even on windows
    2. instead of f.write you could use f.puts, f.print, etc.
    3. another version is:

    f = File.open(',...', 'w')
    f.puts ...
    f.close

    The block version is safer than this as it closes the file
    automatically, even in the case of exception within the block.
     
    Jan Svitok, Oct 20, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. keto
    Replies:
    0
    Views:
    998
  2. J.Ram
    Replies:
    7
    Views:
    660
  3. David Cournapeau

    print a vs print '%s' % a vs print '%f' a

    David Cournapeau, Dec 30, 2008, in forum: Python
    Replies:
    0
    Views:
    373
    David Cournapeau
    Dec 30, 2008
  4. Pavel
    Replies:
    7
    Views:
    546
    Pavel
    Sep 19, 2010
  5. Michael Tan
    Replies:
    32
    Views:
    1,021
    Ara.T.Howard
    Jul 21, 2005
Loading...

Share This Page