简体   繁体   English

增加一个 ruby​​ 字符串插值循环

[英]increment by one ruby string interpolation loop

I am trying to make data variable increments by 1 every time it gets collected in the barcode array.每次在条形码数组中收集data时,我都试图使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

How do I increment data by 1 each time the collect happens?每次收集发生时如何将data增加 1?

Ruby has a handy helper method for "incrementing" strings, called succ / succ! Ruby 有一个方便的辅助方法用于“递增”字符串,称为succ / succ! . . Observe:观察:

serial_number = "00000000"

15.times { puts serial_number.succ! }
# >> 00000001
# >> 00000002
# >> 00000003
# >> 00000004
# >> 00000005
# >> 00000006
# >> 00000007
# >> 00000008
# >> 00000009
# >> 00000010
# >> 00000011
# >> 00000012
# >> 00000013
# >> 00000014
# >> 00000015

Meditate on this:思考这个:

5.times { |i| i } # => 5
5.times.collect{ |i| i * 2 } # => [0, 2, 4, 6, 8]

The documentation for times shows it passes a value each time it iterates.为文档times显示它通过每个迭代了时间的值。

Iterates the given block int times, passing in values from zero to int - 1.迭代给定的块 int 次,将值从 0 传递到 int - 1。

Your question isn't easy to understand because it isn't clear what you want to accomplish.你的问题不容易理解,因为不清楚你想完成什么。 From what I understood you want to increment "00000000" > "00000001", etc.据我了解,您要增加“00000000”>“00000001”等。

For that you could use String.rjust :为此,您可以使用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
}

Best wishes!最好的祝愿!

Update: Sergio Tulentsev's answer is very handy too and even more elegant for this problem, but if you want more control over the serial number, this would be the way.更新: Sergio Tulentsev 的回答也非常方便,对于这个问题甚至更优雅,但如果你想更好地控制序列号,这就是方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM