On Mon, Aug 6, 2012 at 1:01 AM, Fosiul Alam <[email protected]> wrote:
> HI
> i dont know how to get this ..
>
> i put a value in a text file
>
> cat extainfo.txt
> 1008
>
> now i want to get this value from another file
>
> myfile = File.open('extrainfo.txt')
> cuid = myfile.readline

You better change that to

cuid = File.open('extrainfo.txt') {|myfile| myfile.readline}

or if you want to get fancy even

cuid = File.open('extrainfo.txt', &:readline)

Background is that this way the file is properly closed under all circumstances.

You got solutions for the addition issue already.  Of course you can
combine that on one line if you need:

cuid = Integer(File.open('extrainfo.txt', &:readline)) + 1

If you need to write the new id back to the file you need to open the
file in read write mode.  If you want to increment per each run you
can do something like this:

File.open('extrainfo.txt', 'r+') do |io|
  id = io.gets.to_i
  puts id
  io.seek(0)
  io.puts(id + 1)
  io.truncate(io.tell)
end

Note though that this is not safe for concurrent updates.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to