Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如果 some_float 为 nil,我希望结果为 0。我怎么做?
some_float = 9.238 or some_float = nil some_float.round(2)
只需调用.to_f前一轮
.to_f
some_float.to_f.round(2)
因为当你调用to_fnil 时,它会返回0.0
to_f
0.0
9.238.to_f.round(2) # => 9.24 nil.to_f.round(2) # => 0.0
选项1:
x = some_float ? some_float.round(2) : 0.0
选项 2(红宝石 >= 2.3.0):
x = some_float&.round(2) || 0.0