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

Ruby获取Azure用量数据quantity值报错:String转Integer隐式转换失败

解决Azure::Armrest::ArmrestCollection提取quantity值的问题

错误原因解析

  • 你用test["properties"]["quantity"]报错,是因为Azure::Armrest::ArmrestCollection是集合类(类似数组),不是Hash对象。当你用字符串作为键访问时,Ruby会把它当成数组索引(要求整数),所以抛出no implicit conversion of String into Integer错误。
  • 用JSON.parse(test)报错,是因为JSON.parse只接受字符串参数,但test是Ruby对象,不是JSON字符串,自然转换失败。

正确提取步骤

  1. 先确认集合内元素结构
    ArmrestCollection是多个Azure用量数据的集合,先打印第一个元素的结构,明确属性路径:

    puts test.first.inspect
    
  2. 遍历集合提取quantity
    集合里的每个元素是对应的Azure用量模型对象(比如Azure::Armrest::Usage),这类对象的属性通过方法访问,而非Hash键:

    # 提取所有quantity值到数组
    quantities = test.map do |item|
      item.properties.quantity
    end
    
    # 打印结果
    puts quantities.inspect
    

    注:如果模型直接提供了quantity快捷方法,也可以直接写item.quantity,具体以inspect输出的结构为准。

  3. 单个元素提取示例
    如果只需要第一个元素的quantity:

    if test.any?
      puts test.first.properties.quantity
    end
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:09:20