Ruby on Rails调用辛普森API报错TypeError:无法将字符串转为整数
修复方案
该错误的核心原因是:你混淆了API返回的数据结构——https://thesimpsonsquoteapi.glitch.me/quotes 返回的是包含单个哈希对象的数组,而非直接返回哈希。当你用字符串键(比如"quote")去索引数组时,数组要求必须使用整数索引,因此触发了“无法将字符串转为整数”的类型错误。
具体修复步骤
- 先提取数组中的哈希元素:调用API后,通过整数索引(如
[0])获取数组里的唯一哈希对象。 - 再用字符串键访问哈希属性:从哈希对象中提取需要的字段(如
quote、character等)。
示例修正代码
假设你原错误代码类似:
def home response = HTTParty.get("https://thesimpsonsquoteapi.glitch.me/quotes") @quote = response["quote"] # 第13行,此处触发错误 end
修正为:
def home response = HTTParty.get("https://thesimpsonsquoteapi.glitch.me/quotes") quote_data = response[0] # 先获取数组中的哈希元素 @quote = quote_data["quote"] @character = quote_data["character"] end
额外健壮性优化
可添加空值判断,避免API返回异常时触发新错误:
def home response = HTTParty.get("https://thesimpsonsquoteapi.glitch.me/quotes") if response.present? && response[0].is_a?(Hash) quote_data = response[0] @quote = quote_data["quote"] @character = quote_data["character"] else @quote = "Oops, no quote available!" end end
内容的提问来源于stack exchange,提问作者Gusteau
相关产品推荐
相关产品推荐

