剥去字符串的第一个字符

Mat*_*iby 4 ruby ruby-on-rails

我有

string = "$575.00 "
string.to_f
// => 0.0

string = "575.00 "
string.to_f
// => 575.0
Run Code Online (Sandbox Code Playgroud)

进来的值是这种格式,我需要插入一个十进制数据库字段任何建议

"$575.00 " 
Run Code Online (Sandbox Code Playgroud)

wup*_*tah 5

我们这样做经常我们写了一个扩展String名为cost_to_f:

class String
  def cost_to_f
    self.delete('$,').to_f
  end
end
Run Code Online (Sandbox Code Playgroud)

我们存储这样的扩展config/initializers/extensions/string.rb.

然后你可以简单地打电话:

"$5,425.55".cost_to_f   #=> 5425.55
Run Code Online (Sandbox Code Playgroud)

如果你很少使用这种方法,最好的办法就是简单地创建一个函数,因为向核心类添加函数并不是我会轻易推荐的东西:

def cost_to_f(string)
  string.delete('$,').to_f
end
Run Code Online (Sandbox Code Playgroud)

如果您需要多个类,您可以随时将它放在模块中,然后include将模块放在任何需要的地方.


再多一点点.您提到在将字符串写入数据库时​​需要处理该字符串.使用ActiveRecord,最好的方法是:

class Item < ActiveRecord::Base
  def price=(p)
    p = p.cost_to_f if p.is_a?(String)  
    write_attribute(:price, p)
  end
end
Run Code Online (Sandbox Code Playgroud)

编辑:更新使用String#delete!