每次在条形码数组中收集时,我都会尝试将data
变量增加1。
def generate_barcode
batch_number = params[:batch_number].to_i
business_partner_id = params[:business_partner].to_i
current_business_partner = BusinessPartner.find(business_partner_id)
serial_number = "00000000"
final_value = current_business_partner.partner_code << serial_number
barcodes = batch_number.times.collect {
data = "#{final_value + '1'}"
Barby::EAN13.new(data) #currently collecting the same object batch number of times with data value being the same......
}
end
每次收集时,如何将data
增加1?
答案 0 :(得分:3)
Ruby有一个方便的帮助方法,用于&#34;递增&#34;字符串,称为var os = require('os');
var home = os.homedir();
/ succ
。观察:
succ!
答案 1 :(得分:1)
您的问题不容易理解,因为您不清楚自己想要完成什么。根据我的理解,你想增加“00000000”&gt; “00000001”等。
为此你可以使用String.rjust:
number_of_digits = 8
serial_number = 0 # Use an integer!!!
barcodes = batch_number.times.collect {
serial_number += 1
data = serial_number.to_s.rjust(number_of_digits, '0')
# Do what you want with data
}
祝福!
更新:Sergio Tulentsev的回答非常方便,对于这个问题更加优雅,但如果您想要更多地控制序列号,那就是这样。
答案 2 :(得分:0)
默想:
5.times { |i| i } # => 5
5.times.collect{ |i| i * 2 } # => [0, 2, 4, 6, 8]
times
的文档显示每次迭代时都会传递一个值。
迭代给定的块int次数,将值从零传递到int - 1。