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
相关产品推荐
相关产品推荐

