RubyonRails:未能将hash中的值转换为float



我觉得我错过了一些非常明显的东西。

我将以下散列放在变量"simple_lable"中。调用inspect很好,但我似乎无法访问任何数值。to_i为0,.to_f为0.0,to_s为空白

puts "**************************"
puts simple_label.inspect
puts simple_label["margin_top"].to_f
puts simple_label["margin_bottom"].to_f
puts simple_label["margin_right"].to_f
puts simple_label["margin_left"].to_f
puts simple_label["paper_size"]
puts "**************************"

中的结果

**************************
{"paper_size"=>"LETTER", "top_margin"=>36, "bottom_margin"=>36, "left_margin"=>15.822, "right_margin"=>15.822, "columns"=>3, "rows"=>10, "column_gutter"=>15, "row_gutter"=>0}
0.0
0.0
0.0
0.0
LETTER
**************************

所以这些价值观是存在的,但我似乎无法正确掌握它们。

有什么想法吗?

非常感谢。

问题是您的哈希键不正确。例如,您的散列将top_margin作为密钥,但您正试图引用margin_top的密钥。对于不存在的密钥,散列将返回nil,对于nil散列值,to_fto_i为零,to_s为空。

最新更新