# How perform addition a text value with an integer

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’)

puts cuid

but i need to add + 1 with this cuid

i tryed couple of ways… but no luck

Integer(cuid)
cuid = cuid +1
puts cuid

but it through the bellow error

`+’: can’t convert Fixnum into String (TypeError)

how will i increase the value … ??

regards

On 6/08/2012, at 11:01 AM, Fosiul A. wrote:

`+’: can’t convert Fixnum into String (TypeError)
Here a ‘correct’ version of your script.

irb(main):001:0> cuid = “1008”
=> “1008”
irb(main):002:0> new_cuid = Integer cuid
=> 1008
irb(main):003:0> new_cuid += 1
=> 1009
irb(main):004:0> cuid = “#{new_cuid}”
=> “1009”
irb(main):005:0> puts cuid
1009
=> nil

or

irb(main):001:0> cuid = “1008”
=> “1008”
irb(main):002:0> puts “#{Integer(cuid) + 1}”
1009
=> nil

Henry

Try this:

irb(main):001:0> cuid = “1008”
=> “1008”
irb(main):002:0> cuid = “#{cuid.to_i + 1}”
=> “1009”

The problem is that when you call Integer(cuid) or cuid.to_i you don’t
change the type of cuid, it only returns an integer.

On 2012-08-06 01:28, Alex Coplan wrote:

Try this:

irb(main):001:0> cuid = “1008”
=> “1008”
irb(main):002:0> cuid = “#{cuid.to_i + 1}”
=> “1009”

Or cuid.next

Hi thanks for all your help
its works perfect.

On Mon, Aug 6, 2012 at 1:01 AM, Fosiul A. [email protected]
wrote:

myfile = File.open(‘extrainfo.txt’)

You better change that to

or if you want to get fancy even

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