我看到了 Ruby 字符串文档并测试了这些方法。我发现两个相似的方法是 to_sym 和 intern 方法。
"cat".intern
=> :cat
"cat".to_sym
=> :cat
我搜索了 Stack Overflow,令人惊讶的是,还没有人问过这个问题。我自己找不到两者之间的区别,所以我想我会问这个问题。
如果他们做同样的事情,一种方法比另一种更快吗?如果是这样,那么使用该方法就有意义了。
最佳答案
它们似乎是同一事物的别名。来自documentation可以看到intern
的示例代码使用了to_sym
:
intern → symbol
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See
Symbol#id2name
."Koala".intern #=> :Koala s = 'cat'.to_sym #=> :cat s == :cat #=> true s = '@cat'.to_sym #=> :@cat s == :@cat #=> true
This can also be used to create symbols that cannot be represented using the :xxx notation.
'cat and dog'.to_sym #=> :"cat and dog"
关于Ruby - intern 和 to_sym 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24268396/