我想使用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
attr_accessor :2
不可能。2
不是 Ruby 中的有效标识符。但tm
是。
根据您的分数,您可以执行以下操作:
score['2']
但这几乎是您在不更改名称的情况下所能得到的。