我正在使用 sinatra 编写一个小型 ruby 应用程序,并有一个文本输入,然后我使用 .to_f
方法将其转换为平面文本。但是,如果输入为空,.to_f
仍会将空字符串转换为 0 值。
我希望对其进行检查,这样如果输入为空白/空,它就不会尝试将其转换为数字。
下面是我到目前为止的代码,我尝试将 .empty?
添加到末尾,但它会引发方法错误。
weight = Weight.create(
:amount => params[:amount].to_f,
:user_id => current_user.id,
:created_at => Time.now
)
最佳答案
您有两个基本选项。第一种是使用三元运算符,当字符串为空时给出一个默认值。基本模板是:
(params[:amount].empty?) ? <EMPTY EXPRESSION> : <NOT EMPTY EXPRESSION>
例如,当params[:amount]
为空时返回nil
:
weight = Weight.create(
:amount => (params[:amount].empty?) ? nil : params[:amount].to_f,
:user_id => current_user.id,
:created_at => Time.now
)
第二种是使用Ruby 的逻辑运算符。基本模板是:
params[:amount].empty? && <EMPTY EXPRESSION> || <NOT EMPTY EXPRESSION>
例如,当 params[:amount]
为空时引发异常:
weight = Weight.create(
:amount => params[:amount].empty? && \
(raise ArgumentError.new('Bad :amount')) || params[:amount].to_f
:user_id => current_user.id,
:created_at => Time.now
)
两种方式都可以返回nil
或引发异常。选择很大程度上取决于风格。
关于ruby - 检查文本输入是否为空,如果是,则不要转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15615326/