Created
July 8, 2011 20:05
-
-
Save misfo/1072693 to your computer and use it in GitHub Desktop.
valid Symbol literal characters in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ruby -v | |
ruby 1.9.2p136 (2010-12-25) | |
$ ruby symbol_literals.rb | |
valid as first char: | |
@$_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz | |
valid as middle char: | |
_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 | |
valid as end char: | |
!_=?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def symbol_chars_are_valid(symbol_chars) | |
# :aaa == :"aaa" if it has valid Symbol literal chars | |
eval ":#{symbol_chars} == :#{symbol_chars.inspect}" | |
rescue Exception | |
false | |
end | |
chars_to_try = | |
'`~!@$%^&*()-_+={}[]|\;:"<>,.?/'.split('') + ["'"] + | |
('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a | |
puts "valid as first char:" | |
puts chars_to_try.select {|c| symbol_chars_are_valid "#{c}aa" }.join '' | |
puts "valid as middle char:" | |
puts chars_to_try.select {|c| symbol_chars_are_valid "a#{c}a" }.join '' | |
puts "valid as end char:" | |
puts chars_to_try.select {|c| symbol_chars_are_valid "aa#{c}" }.join '' |
don't forget valid single character symbols
puts chars_to_try.select {|c| symbol_chars_are_valid "#{c}" }.join ''
`~!%^&*-_+|<>/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
What about these symbols?
:**
:>=
:[]
:[]=
You could also just escape the '
symbol like so:
`~!@$%^&*()-_+={}[]|\;:"<>\',.?/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pretty much the rule is: A non quoted symbol must make sense in ruby without the colon character (with a few exceptions). If it doesn't you can't use it.
So any identifier for constants (class, module), methods, variables (local, instance, class, global) can be a symbol