BigDecimal的不能被强迫的BigDecimal(BigDecimal can't b

2019-09-17 10:38发布

这应该是很简单的,但它吹起来。 有任何想法吗?

d = BigDecimal.new("2.0")
YAML::load({:a => d}.to_yaml)
TypeError: BigDecimal can't be coerced into BigDecimal
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `block in <module:IRB>'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `call'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `inspect_value'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/context.rb:260:in `inspect_last_value'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:311:in `output_value'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:160:in `block (2 levels) in eval_input'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:273:in `signal_status'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:156:in `block in eval_input'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:243:in `block (2 levels) in each_top_level_statement'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `loop'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `block in each_top_level_statement'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `catch'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `each_top_level_statement'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:155:in `eval_input'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:70:in `block in start'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `catch'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `start'
from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'Maybe IRB bug!

Answer 1:

这是已被错误报道和固定 。

最好的解决办法是升级到最新的Ruby(修复是补丁级别194起)。

如果您无法升级你的Ruby版本,您可以通过安装得到修复精极度紧张的宝石 。 如果你这样做,你需要添加gem 'psych'你之前require 'yaml' (或将其添加到您Gemfile如果你使用捆扎机)从创业板,而不是从标准库加载代码..



Answer 2:

是啊,我遇到了这一回。 这里是什么,我做了一个版本:

YAML和BigDecimal的解决方法



Answer 3:

这里是大卫的回答,更新1.9.3由于上班此相关的问题 :

require 'yaml'
require 'bigdecimal'
YAML::ENGINE.yamler= 'syck'
class BigDecimal
  def to_yaml(opts={})
    YAML::quick_emit(object_id, opts) do |out|
      out.scalar("tag:induktiv.at,2007:BigDecimal", self.to_s)
    end
  end
end
YAML.add_domain_type("induktiv.at,2007", "BigDecimal") do |type, val|
  BigDecimal.new(val)
end
x = BigDecimal.new("2.0")
puts x.to_yaml
y = YAML.load(x.to_yaml)
puts x == y


文章来源: BigDecimal can't be coerced into BigDecimal