Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

dscataglini commented Dec 12, 2012

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

This comment has been minimized.

demosdemon commented Jul 6, 2013

don't forget valid single character symbols

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

This comment has been minimized.

ronalchn commented Oct 23, 2013

What about these symbols?

:**
:>=
:[]
:[]=
@cyzanfar

This comment has been minimized.

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