You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails Helper调用number_to_human报错unexpected tSTRING_BEG如何修复?

Rails自定义货币格式化Helper修复方案

错误原因

你遇到的是Ruby基础语法错误,number_to_human方法的返回值和后续的货币符号字符串之间缺少拼接运算符,同时Ruby支持方法调用省略括号,连续的两个表达式会被误识别为方法传参逻辑,无法被解析因此触发语法报错。

修复代码

你可以选择以下任意一种写法实现字符串拼接需求:

写法1:使用+运算符拼接

def money(value, currency)
  return "N/A" unless value
  number_to_human(value, units: { thousand: 'K', million: 'M' }) + currency.to_s
end

调用to_s是为了兼容currency参数为nil的场景,避免出现无方法报错。

写法2:统一使用字符串插值(更推荐)

def money(value, currency)
  return "N/A" unless value
  "#{number_to_human(value, units: { thousand: 'K', million: 'M' })}#{currency}"
end

如果需要数值和货币符号之间保留空格,只需要在两个插值表达式中间加空格即可:"#{number_to_human(value, units: { thousand: 'K', million: 'M' })} #{currency}"。

内容的提问来源于stack exchange,提问作者Promise Preston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 06:39:04