Reputation: 607
I would like to figure out how to increment a string "0001" inside of a .each ruby on rails model. I'm trying to use the number 0001 to put in a file path for active storage to import a pdf file.
The pdf file is exported from another program that auto increments the file name 0001_file.pdf and I have no way of changing that process.
I tried "0000".next
but the number remains the same "0001".
items.each do |f|
num = "0000".next
f.doc.attach(io: File.open("file/path/#{num}_file.pdf"), filename: "#{num}_file.pdf", content_type: "application/pdf")
end
What is the best way to save the string e.g. "0002" outside of the .each so it can be used to increment for the next iteration?
0001_file.pdf
0002_file.pdf
0003_file.pdf
0004_file.pdf
Upvotes: 0
Views: 265
Reputation: 107
Just add 0 and check the example below. 0001, 0010, 9999, 0919
items.each_with_index do |f, index|
num = sprintf '%04d', index + 1
f.doc.attach(io: File.open("file/path/#{num}_file.pdf"), filename: "#{num}_file.pdf", content_type: "application/pdf")
end
[1,2,3,4].each_with_index do |i, index|
fileName = sprintf '%04d', index + 1
puts fileName
end
Upvotes: 1
Reputation: 186
If the number of digits is less than four it will add leading zeros to make it 4 digits.
n = 4
file_num = 1
items.each do |f|
num = file_num.to_s.rjust(n, '0')
f.doc.attach(io: File.open("file/path/#{num}_file.pdf"), filename: "#{num}_file.pdf", content_type: "application/pdf")
file_num += 1
end
1 will be 0001, 12 will be 0012
Upvotes: 2
Reputation: 1392
May be it isn't a best way but for workaround you can do like this
val = "000"
items.each.with_index(1) do |f, index|
num = val + index.to_s
f.doc.attach(io: File.open("file/path/#{num}_file.pdf"), filename: "#{num}_file.pdf", content_type: "application/pdf")
end
This should result incremented value of num in each iteration like this 0001, 0002, 0003
Upvotes: -1