ruby - 如何在红宝石中使用数字作为符号
问题描述
我想使用 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']
但这几乎是您在不更改名称的情况下所能得到的。
推荐阅读
- unity3d - 混合树在 2d 中很糟糕
- java - Selenium Webdriver:如何检查特定屏幕上是否存在 ui 元素,无论它当前是否可见/可点击
- angular - Angular 2有方法打印出svg多边形点
- gradle - Gradle 6 settings.gradle.kts 属性问题
- json - Scala Spark - 将 JSON 列拆分为多列
- ssl - .net core WebAPI 为 Intranet 启用 SSL
- wpf - NuGet 还原前解决方案以使 wix 在 Azure Devops 中失败
- java - 指定 AWS Cloudwatch 日志客户端的凭证
- swift - 每次编译他们正在测试的目标时运行单元测试
- android - 如何在 Android 设备上运行 VS Code