首页 > 解决方案 > 如何在红宝石中使用数字作为符号

问题描述

我想使用 JSON API。它有一个数字对象,但我不知道如何使用它。

JSON 看起来像这样:

"scores": {
  "2": {
    "home": "2",
    "away": "0"
   }
}

我的 Ruby 代码如下所示:

class Score < Base
  attr_accessor :2
end

def parse_scores(args = {})
  Score.new(args.fetch("scores", {}))
end

相同类型的代码在 JSON 如下所示的另一个类中工作:

"timer": {
    "tm": 86,
    "ts": 4,
    "tt": "1"
}

Ruby 代码如下所示:

class Timer < Base
  attr_accessor :tm, :ts, :tt       
end

def parse_timer(args = {})
  Timer.new(args.fetch("timer", {}))
end

该类Base如下所示:

class Base
  attr_accessor :errors

  def initialize(args = {})
    args.each do |name, value|
      attr_name = name.to_s 
      send("#{attr_name}=", value) if respond_to?("#{attr_name}=")
    end
  end
end

我找到了这个解决方案(感谢大家的帮助):

 module Betsapi
  class Score < Base
    attr_accessor :fulltime
    def initialize(args = {})
      super(args)
      self.fulltime = args['2']
   end
  end
end

标签: ruby

解决方案


 attr_accessor :2

不可能。2不是 ruby​​ 中的有效标识符。但是tm是。

根据您的分数到底是多少,您可以执行以下操作:

 score['2']

但这几乎是您在不更改名称的情况下所能得到的。


推荐阅读