根据字符数拆分Ruby on Rails

时间:2014-07-27 15:52:35

标签: ruby-on-rails ruby ruby-on-rails-3

我想拆分这些数字

a = 900000 
b = 1800000 
c = 5000 

进入这些

  

a [0] = 900

     

a [1] = 000

     

b [0] = 1800

     

b [1] = 000

     

c [0] = 5

     

c [1] = 000

我怎么可能这样做?

3 个答案:

答案 0 :(得分:7)

String#[]与范围:

一起使用
a = 1800000 
[a.to_s[0...-3], a.to_s[-3..-1]]
# => ["1800", "000"]

使用Numeric#divmod

a.divmod(1000)
# => [1800, 0]
a.divmod(1000).map { |n| '%03d' % n }
# => ["1800", "000"]

使用正则表达式:

a.to_s.match(/(.*)(.{3})$/).captures
# => ["1800", "000"]

答案 1 :(得分:0)

b.to_s.chars[0..-4].join

b.to_s.chars.last(3).join

答案 2 :(得分:-1)

这是rails NumberHelper的number_with_delimiter方法的源代码

# File actionpack/lib/action_view/helpers/number_helper.rb, line 263
def number_with_delimiter(number, options = {})
  options.symbolize_keys!

  options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter]
  options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator]

  begin
    Float(number)
  rescue ArgumentError, TypeError
    if options[:raise]
      raise InvalidNumberError, number
    else
      return number
    end
  end

  defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  options = options.reverse_merge(defaults)

  parts = number.to_s.to_str.split('.')
  parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
  parts.join(options[:separator]).html_safe
end

我觉得你找的代码就是这个

parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")