将字符串转换为关键字
我们可以轻松地将关键字转换为字符串:
true.to_s
=> "true"
但是如何将字符串转换为关键字呢?
We can easily convert a keyword into a string:
true.to_s
=> "true"
But how to convert a string into a keyword?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你有多少个关键词?您对“关键字”的定义是什么?
我会用 case-命令来实现。您可以为字符串定义一个
to_keyword
方法。我的实现检测 true、false、nil(或 NULL)。检测到字符串,忽略大写字母(TRUE 也将是true
)。其他字符串将返回一个符号(字符串本身将是另一个合理的结果)。该示例可以适用于更多“关键字”或其他结果。
How many keywords do you have? What's your definition of a 'keyword'?
I would implement with a case-command. You may define a
to_keyword
method for String. My implementation detects true, false, nil (or NULL). The strings are detected, ignoring capitals (TRUE will also betrue
) Other strings will return a symbol (The string itself would be another reasonable result).The example can be adapted for further 'keywords' or other results.
试试这个:
try this:
你可以尝试yaml:
You could try yaml:
我最喜欢克努特的答案。但我认为我不会支持“Null”和其他内容。
这是这个版本,稍微简单一些。
不过这个问题非常简单。在你的测试中你可以简单地
I like Knut's answers mostly. I don't think I would support "Null" and others though.
Here is this version which is a little more simple.
This problem is pretty straight forward though. In your tests you could simply
根据您的评论,您可以执行类似的操作:
Following your comment, you could do something like that :