如何防止 yaml 中的字符串转换为时间
我有一个 yaml 文件,其中包含一些时间:
hours:
- 00:00:00
- 00:30:00
- 01:00:00
但是一旦我读到它们,它们就会转换为时间(以秒为单位),但我希望它们暂时保留为字符串,以便我可以进行转换。这是我阅读它们的方式:
def daily_hours
DefaultsConfig.hours.collect {|hour|
logger.info { hour.to_s }
}
end
它的输出:
0 1800 3600
但我希望字符串保持不变,以便我可以将它们转换为时间,例如:
12:00am 12:30am 1:00am
为什么它们会自动转换,我该如何阻止它?
这是 DefaultConfig 类:
class DefaultsConfig
def self.load
config_file = File.join(Rails.root, "config", "defaults.yml")
if File.exists?(config_file)
config = ERB.new(File.read(config_file)).result
config = YAML.load(config)[Rails.env.to_sym]
config.keys.each do |key|
cattr_accessor key
send("#{key}=", config[key])
end
end
end
end
DefaultsConfig.load
I have a yaml file which contains some times:
hours:
- 00:00:00
- 00:30:00
- 01:00:00
But as soon as I read them they get converted to time (in seconds), but I want them to remain as strings for a moment so i can do the conversion. Here's how I'm reading them:
def daily_hours
DefaultsConfig.hours.collect {|hour|
logger.info { hour.to_s }
}
end
And it's outputting:
0 1800 3600
But I want the strings to remain unchanged to I can convert them to times such as:
12:00am 12:30am 1:00am
Why are they getting converted automatically, and how can I stop it?
Here's the DefaultConfig class:
class DefaultsConfig
def self.load
config_file = File.join(Rails.root, "config", "defaults.yml")
if File.exists?(config_file)
config = ERB.new(File.read(config_file)).result
config = YAML.load(config)[Rails.env.to_sym]
config.keys.each do |key|
cattr_accessor key
send("#{key}=", config[key])
end
end
end
end
DefaultsConfig.load
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果将该值括在单引号内,YAML 解析器会将该值视为字符串。
现在,当您访问该值时,您将得到一个字符串而不是时间
If you enclose the value within single quotes, the YAML parser will treat the value as a string.
Now when you access the value you will get a string instead of time
不带引号或标签的标量是隐式类型的主题。您可以使用引号或显式标记:
Scalar without quotes or tag is a subject of implicit type. You can use quotes or explicit tag: