Skip to content

Instantly share code, notes, and snippets.

@misfo
Created July 8, 2011 20:05
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save misfo/1072693 to your computer and use it in GitHub Desktop.
Save misfo/1072693 to your computer and use it in GitHub Desktop.
valid Symbol literal characters in Ruby
$ 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
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 ''
@dscataglini
Copy link

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

@demosdemon
Copy link

don't forget valid single character symbols

puts chars_to_try.select {|c| symbol_chars_are_valid "#{c}" }.join ''
`~!%^&*-_+|<>/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

@ronalchn
Copy link

What about these symbols?

:**
:>=
:[]
:[]=

@cyzanfar
Copy link

cyzanfar commented May 1, 2015

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