Ruby方法"to_sym"有什么作用? [英] What does the Ruby method 'to_sym' do?
问题描述
to_sym
方法有什么作用?它是做什么用的?
What does the to_sym
method do? What is it used for?
推荐答案
to_sym
将字符串转换为符号.例如,"a".to_sym
变为:a
.
to_sym
converts a string to a symbol. For example, "a".to_sym
becomes :a
.
它不是特定于Rails的;香草红宝石也有.
It's not specific to Rails; vanilla Ruby has it as well.
在某些版本的Ruby中,符号也可以与Fixnum相互转换.但是来自ruby-lang.org的Ruby 1.9.2-p0中的irb
不允许这样做,除非您将自己的to_sym
方法添加到Fixnum中.我不确定Rails是否会这样做,但是在任何情况下它似乎都不太有用.
It looks like in some versions of Ruby, a symbol could be converted to and from a Fixnum as well. But irb
from Ruby 1.9.2-p0, from ruby-lang.org, doesn't allow that unless you add your own to_sym
method to Fixnum. I'm not sure whether Rails does that, but it doesn't seem very useful in any case.
这篇关于Ruby方法"to_sym"有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!