Ruby Study 12 : Symbols-阿里云开发者社区

开发者社区> 德哥> 正文

Ruby Study 12 : Symbols

简介:
+关注继续查看
本章主要讲解Symbol 类. 讲解Symbol比较重要的是大家需要了解object_id的知识.
Symbol和Fixnum很相似, 同样的symbol它们的object_id是一致的, 而字符串则不是这样的, 举个例子来回忆一下:
v1 = :name
p v1
p v1.object_id
p :name.object_id
v2 = "name"
p v2
p v2.object_id
p "name".object_id
v3 = 10
p v3
p v3.object_id
p 10.object_id

输出 :
:name
12392
12392
"name"
16803144
16803060
10
21
21

注意不能再给symbol 对象赋值, 因为它和Fixnum object类似就是一个值(可以这么来理解, 例如10它是一个值, 不能给10赋值吧).
:name = "abc"
报错 
C:/Users/digoal/Desktop/new.rb:1: syntax error, unexpected '=', expecting $end
:name = "abc[Finished]"
       ^


10 = 10
报错
C:/Users/digoal/Desktop/new.rb:1: syntax error, unexpected '=', expecting $end
10 = 10
    ^

Symbol在以前我们讲Class的时候有用到过, 例如
class Myclass1
  attr_accessor(:x, :y)
  def initialize(a,b)
    @x = a
    @y = b
  end
end

m1 = Myclass1.new('digoal','zhou')
p m1.x
p m1.y
m1.x= 'DIGOAL'
m1.y= 'ZHOU'
p m1.x
p m1.y


1. Symbols is not Strings
前面已经讲过了, 相同的String的object_id是不一样的, Symbol更像Fixnum . 值相同它们的object_id就相同. 使用equal?方法很容易分辨:
p "abc".equal?("abc")
p 10.equal?(10)
p :name.equal?(:name)
输出
false
true
true

因此Symbol用于类似这种对象相等的比较的场合比较OK, 不会有歧义. 例如 :
def amethod( doThis )
    if (doThis == :deletefiles) then
       puts( 'Now deleting files...')
    elsif (doThis == :formatdisk) then
       puts( 'Now formatting disk...')
    else
        puts( "Sorry, command not understood." )
    end
end

def bmethod( doThis )
case doThis 
    when :deletefiles then puts( 'Now deleting files...')
    when :formatdisk then puts( 'Now formatting disk...')
    else  puts( "Sorry, command not understood." )
end
end
amethod(:formatdisk)
bmethod(:deletefiles)
结果
Now formatting disk...
Now deleting files...

书上还介绍了symbol的另一种应用场合, 动态编程(广泛用于rails), 例如 : 
module One
    class Fred
    end
    $f1 = :Fred
    def self.evalFred( aSymbol )
        puts( eval( aSymbol.id2name ) )     # id2name 是Symbol class public instance method, 用于返回symbol对应的字符串类型的对象.
    end
end
module Two
    Fred = 1
    $f2 = :Fred
    def self.evalFred( aSymbol )
        puts( eval( aSymbol.id2name ) )      
    end
end
def Fred()
    puts( "hello from the Fred method" )
end
$f3 = :Fred

One::evalFred( $f1 )   # 调用Module的singleton method用两个冒号.
输出
One::Fred

Two::evalFred( $f2 )
输出
1

method($f3).call
输出
hello from the Fred method
# 不管用哪个全局变量, 结果都一样, 它们的值都是:Fred, object_id也都一样.
One::evalFred( :Fred )  #=> One::Fred
Two::evalFred( :Fred )  #=> 1
method(:Fred).call      #=> hello from the Fred method


eval是Kernel的一个public instance method, 它把传递给它的参数当可执行代码执行.
eval的用法 :
eval(string [, binding [, filename [,lineno]]]) → obj click to toggle source 
Evaluates the Ruby expression(s) in string. If binding is given, which must be a Binding object, the evaluation is performed in its context. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors. 

   def get_binding(str)
     return binding
   end
   str = "hello"
   eval "str + ' Fred'"                      #=> "hello Fred"
   eval "str + ' Fred'", get_binding("bye")  #=> "bye Fred"


2. Symbols and Variables
这里举一些例子, 怎么让symbol和variable联系起来.
例1 :
x = 1
xsymbol = :x
def amethod( somearg )
    p( somearg )
end
amethod(eval(xsymbol.id2name))
amethod( eval( ( eval(:xsymbol.id2name)).id2name ) )
method(:amethod).call("abc")  # 这里的call是Method 的public instance method
输出
1
1
"abc"

Method 的public instance method, call介绍 : 
call(args, ...) → obj meth[args, ...] → obj click to toggle source 
Invokes the meth with the specified arguments, returning the method’s return value. 

   m = 12.method("+")
   m.call(3)    #=> 15
   m.call(20)   #=> 32

Object 的public instance method(返回Method 对象), method介绍 :
method(sym) → method click to toggle source 
Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj's object instance, so instance variables and the value of self remain available.

   class Demo
     def initialize(n)
       @iv = n
     end
     def hello()
       "Hello, @iv = #{@iv}"
     end
   end

   k = Demo.new(99)
   m = k.method(:hello)
   m.call   #=> "Hello, @iv = 99"

   l = Demo.new('Fred')
   m = l.method("hello")
   m.call   #=> "Hello, @iv = Fred"

例2 : 
def mymethod( somearg )
   print( "I say: " << somearg )
end
this_is_a_method_name = method(:mymethod)
puts( this_is_a_method_name )
puts( "#{this_is_a_method_name.class}" )
this_is_a_method_name.call( "hello world" )
输出 : 
#<Method: Object#mymethod>
Method
I say: hello world


3. Why use Symbols?
为什么要使用Symbol, 只能说它在rails的应用中比较广泛, 具体为什么可能是它的灵活性.
另外某些特殊场景下也会用到.
例如 : 
用它来调用方法, 某些输出的方法是以symbol组成的array的. 有些时候也会用symbol作为hash的key.
{ :text => "Hello world" }

使用define_method方法创建方法, 第一个参数是symbol, 方法名. 第二个参数可以是block, 它是这个定义的方法的执行体.
class Array
    define_method( :aNewMethod, lambda{ 
        |*args| puts( args.inspect) 
    } ) 
end

p Array.method_defined?( :aNewMethod )  # 查看这个方法是否被定义, 因为Array.class = Class, Class.superclass=Module, 所以Array可以调用method_defined?方法.
[].aNewMethod( 1,2,3 )
class Array
    remove_method( :aNewMethod )  # 移除定义的方法.
end

输出
true
[1, 2, 3]

define_method, remove_method 是Module class的priviate instance method. method_defined? 是Module class的public instance method.
define_method(symbol, method) → new_method  define_method(symbol) { block } → proc   
Defines an instance method in the receiver. The method parameter can  be a Proc, a Method or an UnboundMethod object. If a  block is specified, it is used as the method body. This block is evaluated using  instance_eval, a point that is tricky to demonstrate because define_method is private.  (This is why we resort to the send hack in this example.) 
class A      
def fred        
puts "In Fred"      
end      
def create_method(name, &block)        
self.class.send(:define_method, name, &block)      
end      
define_method(:wilma) { puts "Charge it!" }    
end    
class B < A      
define_method(:barney, instance_method(:fred))    
end    
a = B.new    
a.barney    
a.wilma    
a.create_method(:betty) { p self }    
a.betty  
produces: 
In Fred    
Charge it!    
#<B:0x401b39e8>


4. What is a Symbol?
A symbol is, in fact, a pointer into the symbol table. The symbol table is Ruby’s internal list of known identifiers—such as variable and method names.
1.9 打印系统中的Symbol:
p( Symbol.all_symbols.sort )
[:"", :!, :!=, :!~, :"\#$!", :$!, :$", :$$, :$&, :$', :$*, :$+, :$,, :$-0, :$-F, :$-I, :$-K, :$-W, :$-a, :$-d, :$-i, :$-l, :$-p, :$-v, :$-w, :$., :$/, :$0, :$:, :$;, :$<, :$=, :$>, :$?, :$@, :$DEBUG, :$FILENAME, :$KCODE, :$LOADED_FEATURES, :$LOAD_PATH, :$PROGRAM_NAME, :$SAFE, :$VERBOSE, :$\, :$_, :$`, :$stderr, :$stdin, :$stdout, :$~, :%, :&, :*, :**, :+, :+@, :-, :-@, :/, :<, :<<, :<=, :<=>, :"<CFUNC>", :"<IFUNC>", :==, :===, :=~, :>, :>=, :>>, :@@source_index, :@@win_platform, :@config_file, :@configuration, :@default_dir, :@errors, :@exit_code, :@file_path, :@gem_prelude_index, :@host, :@loaded_specs, :@name, :@paths, :@platforms, :@post_build_hooks, :@post_install_hooks, :@post_reset_hooks, :@post_uninstall_hooks, :@pre_install_hooks, :@pre_reset_hooks, :@pre_uninstall_hooks, :@requirement, :@ruby, :@ruby_version, :@searcher, :@skip, :@source_index, :@sources, :@spec, :@suffix_pattern, :@suffixes, :@unresolved_deps, :@user_home, :@version, :AFTER_OUTPUT, :ALT_SEPARATOR, :ANSI_X3_4_1968, :APPEND, :ARGF, :ARGV, :ASCII, :ASCII_8BIT, :ArgumentError, :Array, :BIG5, :BIG5_HKSCS, :BIG5_HKSCS_2008, :BIG5_UAO, :BINARY, :BasicObject, :Big5, :Big5_HKSCS, :Big5_HKSCS_2008, :Big5_UAO, :Bignum, :Binding, :Builder, :CONFIG, :CP1250, :CP1251, :CP1252, :CP1253, :CP1254, :CP1255, :CP1256, :CP1257, :CP1258, :CP437, :CP50220, :CP50221, :CP51932, :CP65000, :CP65001, :CP737, :CP775, :CP850, :CP852, :CP855, :CP857, :CP860, :CP861, :CP862, :CP863, :CP864, :CP865, :CP866, :CP869, :CP874, :CP878, :CP932, :CP936, :CP949, :CP950, :CP951, :CREAT, :CRLF_NEWLINE_DECORATOR, :CROSS_COMPILING, :CR_NEWLINE_DECORATOR, :CSWINDOWS31J, :Cache, :Class, :CommandLineError, :Comparable, :CompatibilityError, :Complex, :Config, :ConfigFile, :ConfigMap, :Constants, :Converter, :ConverterNotFoundError, :CsWindows31J, :DEFAULT, :DESTDIR, :DIG, :Data, :Default, :DefaultUserInteraction, :Deflate, :Dependency, :DependencyError, :DependencyList, :DependencyRemovalException, :Deprecate, :Dir, :DocumentError, :DomainError, :E, :E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, :EADV, :EAFNOSUPPORT, :EAGAIN, :EALREADY, :EAUTH, :EBADE, :EBADF, :EBADFD, :EBADMSG, :EBADR, :EBADRPC, :EBADRQC, :EBADSLT, :EBFONT, :EBUSY, :ECANCELED, :ECHILD, :ECHRNG, :ECOMM, :ECONNABORTED, :ECONNREFUSED, :ECONNRESET, :EDEADLK, :EDEADLOCK, :EDESTADDRREQ, :EDOM, :EDOOFUS, :EDOTDOT, :EDQUOT, :EEXIST, :EFAULT, :EFBIG, :EFTYPE, :EHOSTDOWN, :EHOSTUNREACH, :EIDRM, :EILSEQ, :EINPROGRESS, :EINTR, :EINVAL, :EIO, :EIPSEC, :EISCONN, :EISDIR, :EISNAM, :EKEYEXPIRED, :EKEYREJECTED, :EKEYREVOKED, :EL2HLT, :EL2NSYNC, :EL3HLT, :EL3RST, :ELIBACC, :ELIBBAD, :ELIBEXEC, :ELIBMAX, :ELIBSCN, :ELNRNG, :ELOOP, :EMACS_MULE, :EMEDIUMTYPE, :EMFILE, :EMLINK, :EMSGSIZE, :EMULTIHOP, :ENAMETOOLONG, :ENAVAIL, :ENEEDAUTH, :ENETDOWN, :ENETRESET, :ENETUNREACH, :ENFILE, :ENOANO, :ENOATTR, :ENOBUFS, :ENOCSI, :ENODATA, :ENODEV, :ENOENT, :ENOEXEC, :ENOKEY, :ENOLCK, :ENOLINK, :ENOMEDIUM, :ENOMEM, :ENOMSG, :ENONET, :ENOPKG, :ENOPROTOOPT, :ENOSPC, :ENOSR, :ENOSTR, :ENOSYS, :ENOTBLK, :ENOTCONN, :ENOTDIR, :ENOTEMPTY, :ENOTNAM, :ENOTRECOVERABLE, :ENOTSOCK, :ENOTSUP, :ENOTTY, :ENOTUNIQ, :ENV, :ENXIO, :EOFError, :EOPNOTSUPP, :EOVERFLOW, :EOWNERDEAD, :EPERM, :EPFNOSUPPORT, :EPIPE, :EPROCLIM, :EPROCUNAVAIL, :EPROGMISMATCH, :EPROGUNAVAIL, :EPROTO, :EPROTONOSUPPORT, :EPROTOTYPE, :EPSILON, :ERANGE, :EREMCHG, :EREMOTE, :EREMOTEIO, :ERESTART, :ERFKILL, :EROFS, :ERPCMISMATCH, :ESHUTDOWN, :ESOCKTNOSUPPORT, :ESPIPE, :ESRCH, :ESRMNT, :ESTALE, :ESTRPIPE, :ETIME, :ETIMEDOUT, :ETOOMANYREFS, :ETXTBSY, :EUCCN, :EUCJP, :EUCJP_MS, :EUCKR, :EUCLEAN, :EUCTW, :EUC_CN, :EUC_JP, :EUC_JP_MS, :EUC_KR, :EUC_TW, :EUNATCH, :EUSERS, :EWOULDBLOCK, :EXCL, :EXDEV, :EXEEXT, :EXFULL, :EXTENDED, :Emacs_Mule, :Encoding, :EncodingError, :EndOfYAMLException, :Enumerable, :Enumerator, :Env, :Errno, :EucCN, :EucJP, :EucJP_ms, :EucKR, :EucTW, :Exception, :FALSE, :FIXEDENCODING, :FNM_CASEFOLD, :FNM_DOTMATCH, :FNM_NOESCAPE, :FNM_PATHNAME, :FNM_SYSCASE, :FalseClass, :Fiber, :FiberError, :File, :FilePermissionError, :FileTest, :FileUtils, :Fixnum, :Float, :FloatDomainError, :FormatException, :GB12345, :GB18030, :GB1988, :GBK, :GC, :GEM_PRELUDE_SUCKAGE, :GID, :Gem, :GemNotFoundException, :GemNotInHomeException, :GemPathSearcher, :Generator, :GzipReader, :GzipWriter, :Hash, :I, :IBM437, :IBM737, :IBM775, :IBM850, :IBM852, :IBM855, :IBM857, :IBM860, :IBM861, :IBM862, :IBM863, :IBM864, :IBM865, :IBM866, :IBM869, :IGNORECASE, :INFINITY, :INSTRUCTION_NAMES, :INVALID_MASK, :INVALID_REPLACE, :IO, :IOError, :ISO2022_JP, :ISO2022_JP2, :ISO8859_1, :ISO8859_10, :ISO8859_11, :ISO8859_13, :ISO8859_14, :ISO8859_15, :ISO8859_16, :ISO8859_2, :ISO8859_3, :ISO8859_4, :ISO8859_5, :ISO8859_6, :ISO8859_7, :ISO8859_8, :ISO8859_9, :ISO_2022_JP, :ISO_2022_JP_2, :ISO_2022_JP_KDDI, :ISO_8859_1, :ISO_8859_10, :ISO_8859_11, :ISO_8859_13, :ISO_8859_14, :ISO_8859_15, :ISO_8859_16, :ISO_8859_2, :ISO_8859_3, :ISO_8859_4, :ISO_8859_5, :ISO_8859_6, :ISO_8859_7, :ISO_8859_8, :ISO_8859_9, :IndexError, :Inflate, :InstallError, :InstructionSequence, :Integer, :Interrupt, :InvalidByteSequenceError, :InvalidSpecificationException, :KOI8_R, :KOI8_U, :Kernel, :KeyError, :LOCK_EX, :LOCK_NB, :LOCK_SH, :LOCK_UN, :LoadError, :LocalJumpError, :MACCENTEURO, :MACCROATIAN, :MACCYRILLIC, :MACGREEK, :MACICELAND, :MACJAPAN, :MACJAPANESE, :MACROMAN, :MACROMANIA, :MACTHAI, :MACTURKISH, :MACUKRAINE, :MAJOR_VERSION, :MAKEFILE_CONFIG, :MANT_DIG, :MARSHAL_SPEC_DIR, :MAX, :MAX_10_EXP, :MAX_EXP, :MIN, :MINOR_VERSION, :MIN_10_EXP, :MIN_EXP, :MULTILINE, :MUTEX_FOR_THREAD_EXCLUSIVE, :MacCentEuro, :MacCroatian, :MacCyrillic, :MacGreek, :MacIceland, :MacJapan, :MacJapanese, :MacRoman, :MacRomania, :MacThai, :MacTurkish, :MacUkraine, :Marshal, :MatchData, :Math, :Method, :Module, :Mutex, :NAN, :NIL, :NOENCODING, :NOERROR, :NONBLOCK, :NULL, :NameError, :NilClass, :NoMemoryError, :NoMethodError, :NotImplementedError, :Numeric, :OPTS, :Object, :ObjectSpace, :OperationNotSupportedError, :PARTIAL_INPUT, :PATH_SEPARATOR, :PCK, :PI, :Path, :PathSupport, :Platform, :Proc, :Process, :Profiler, :QUICKLOADER_SUCKAGE, :QuickLoader, :RADIX, :RDONLY, :RDWR, :ROUNDS, :RUBY, :RUBYGEMS_DIR, :RUBY_COPYRIGHT, :RUBY_DESCRIPTION, :RUBY_ENGINE, :RUBY_FRAMEWORK_VERSION, :RUBY_PATCHLEVEL, :RUBY_PLATFORM, :RUBY_RELEASE_DATE, :RUBY_REVISION, :RUBY_VERSION, :Random, :Range, :RangeError, :Rational, :RbConfig, :RbConfigPriorities, :Regexp, :RegexpError, :RemoteError, :RemoteInstallationCancelled, :RemoteInstallationSkipped, :RemoteSourceException, :Requirement, :RubyGemsPackageVersion, :RubyGemsVersion, :RubyVM, :RuntimeError, :SCRIPT_LINES__, :SEEK_CUR, :SEEK_END, :SEEK_SET, :SEPARATOR, :SHIFT_JIS, :SJIS, :SJIS_DOCOMO, :SJIS_DoCoMo, :SJIS_KDDI, :SJIS_SOFTBANK, :SJIS_SoftBank, :STATELESS_ISO_2022_JP, :STATELESS_ISO_2022_JP_KDDI, :STDERR, :STDIN, :STDOUT, :ScriptError, :SecurityError, :Separator, :Shift_JIS, :Signal, :SignalException, :SourceIndex, :SpecFetcher, :Specification, :StandardError, :Stat, :Stateless_ISO_2022_JP, :Stateless_ISO_2022_JP_KDDI, :Status, :StopIteration, :String, :StringIO, :Struct, :Syck, :Symbol, :SyntaxError, :Sys, :SystemCallError, :SystemExit, :SystemExitException, :SystemStackError, :TIS_620, :TMP_RUBY_PREFIX, :TOPDIR, :TOPLEVEL_BINDING, :TRUE, :TRUNC, :Thread, :ThreadError, :ThreadGroup, :Time, :Tms, :TrueClass, :TypeError, :UCS_2BE, :UCS_4BE, :UCS_4LE, :UID, :UNDEF_HEX_CHARREF, :UNDEF_MASK, :UNDEF_REPLACE, :UNIVERSAL_NEWLINE_DECORATOR, :USAGE_ANALYSIS_INSN, :USAGE_ANALYSIS_INSN_BIGRAM, :USAGE_ANALYSIS_REGS, :US_ASCII, :UTF8_DOCOMO, :UTF8_DoCoMo, :UTF8_KDDI, :UTF8_MAC, :UTF8_SOFTBANK, :UTF8_SoftBank, :UTF_16, :UTF_16BE, :UTF_16LE, :UTF_32, :UTF_32BE, :UTF_32LE, :UTF_7, :UTF_8, :UTF_8_HFS, :UTF_8_MAC, :UnboundMethod, :UndefinedConversionError, :VERSION, :VerificationError, :Version, :WINDOWS_1250, :WINDOWS_1251, :WINDOWS_1252, :WINDOWS_1253, :WINDOWS_1254, :WINDOWS_1255, :WINDOWS_1256, :WINDOWS_1257, :WINDOWS_1258, :WINDOWS_31J, :WINDOWS_874, :WIN_PATTERNS, :WNOHANG, :WRONLY, :WUNTRACED, :WaitReadable, :WaitWritable, :Windows_1250, :Windows_1251, :Windows_1252, :Windows_1253, :Windows_1254, :Windows_1255, :Windows_1256, :Windows_1257, :Windows_1258, :Windows_31J, :Windows_874, :XML_ATTR_CONTENT_DECORATOR, :XML_ATTR_QUOTE_DECORATOR, :XML_TEXT_DECORATOR, :YAML, :Yielder, :ZeroDivisionError, :Zlib, :[], :[]=, :^, :_, :__attached__, :__autoload__, :__callee__, :__classid__, :__classpath__, :__id__, :__members__, :__method__, :__recursive_key__, :__send__, :__tmp_classpath__, :_alloc, :_deprecated_activate, :_deprecated_activate_dep, :_deprecated_activate_spec, :_deprecated_all_load_paths, :_deprecated_all_partials, :_deprecated_available?, :_deprecated_cache, :_deprecated_cache_dir, :_deprecated_cache_gem, :_deprecated_default_system_source_cache_dir, :_deprecated_default_user_source_cache_dir, :_deprecated_latest_load_paths, :_deprecated_promote_load_path, :_deprecated_report_activate_error, :_deprecated_required_location, :_deprecated_searcher, :_deprecated_source_index, :_dump, :_dump_data, :_id2ref, :_load, :_load_data, :`, :abort, :abort_on_exception, :abort_on_exception=, :abs, :abs2, :absolute_path, :acos, :acosh, :activate, :activate_dep, :activate_spec, :activated?, :add, :add_trace_func, :advise, :after_output, :alias_method, :aliases, :alive?, :all?, :all_load_paths, :all_partials, :all_symbols, :allocate, :ancestors, :angle, :any?, :append_features, :arg, :args, :argv, :arity, :ascii_compatible?, :ascii_only?, :asciicompat_encoding, :asctime, :asin, :asinh, :assoc, :at, :at_exit, :atan, :atan2, :atanh, :atime, :attr, :attr_accessor, :attr_reader, :attr_writer, :autoclose, :autoclose=, :autoclose?, :autoload, :autoload?, :available?, :backtrace, :base, :basename, :begin, :between?, :bin_file, :bin_path, :binary_mode, :bind, :binding, :bindir, :binmode, :binmode?, :binread, :binwrite, :blksize, :block, :block_given?, :blockdev?, :blocks, :bt, :bytes, :bytesize, :byteslice, :cache, :cache_dir, :cache_gem, :call, :caller, :capitalize, :capitalize!, :captures, :casecmp, :casefold?, :catch, :cbrt, :ceil, :center, :change_privilege, :chardev?, :chars, :chdir, :check_load_path, :chmod, :chomp, :chomp!, :chop, :chop!, :chown, :chr, :chroot, :chunk, :class, :class_eval, :class_exec, :class_variable_defined?, :class_variable_get, :class_variable_set, :class_variables, :clear, :clear_paths, :clone, :close, :close_on_exec, :close_on_exec=, :close_on_exec?, :close_read, :close_write, :closed?, :cm, :codepoints, :coerce, :collect, :collect!, :collect_concat, :combination, :compact, :compact!, :compare_by_identity, :compare_by_identity?, :compatible?, :compile, :compile_file, :compile_option, :compile_option=, :concat, :config, :config_file, :configuration, :configuration=, :conj, :conjugate, :const_defined?, :const_get, :const_missing, :const_set, :constants, :contains_requirable_file?, :convert, :convpath, :copy_stream, :"core#define_method", :"core#define_singleton_method", :"core#set_method_alias", :"core#set_postexe", :"core#set_variable_alias", :"core#undef_method", :coredump?, :cos, :cosh, :count, :count_objects, :cover?, :cr_newline, :crlf_newline, :crypt, :cstime, :ctime, :current, :curry, :custom_dir, :cutime, :cycle, :daemon, :data, :datadir, :day, :default, :default=, :default_bindir, :default_dir, :default_exec_format, :default_external, :default_external=, :default_internal, :default_internal=, :default_path, :default_proc, :default_proc=, :default_sources, :default_system_source_cache_dir, :default_user_source_cache_dir, :define_finalizer, :define_method, :define_singleton_method, :deflate, :delete, :delete!, :delete_at, :delete_if, :denominator, :dep, :dependency, :deprecate, :destination_buffer_full, :destination_encoding, :destination_encoding_name, :detach, :details, :detect, :dev, :dev_major, :dev_minor, :dir, :directory?, :dirname, :dirs, :disable, :disasm, :disassemble, :display, :div, :divmod, :dontneed, :downcase, :downcase!, :downto, :drop, :drop_while, :dst?, :dummy?, :dump, :dup, :e, :each, :each_byte, :each_char, :each_codepoint, :each_cons, :each_entry, :each_index, :each_key, :each_line, :each_load_path, :each_object, :each_pair, :each_slice, :each_value, :each_with_index, :each_with_object, :egid, :egid=, :eid, :eid=, :elapsed, :empty?, :enable, :enabled?, :enclose, :enclosed?, :encode, :encode!, :encoding, :end, :end_with?, :ensure_gem_subdirectories, :entries, :enum_for, :env, :eof, :eof?, :eql?, :equal?, :erf, :erfc, :errno, :error, :error_bytes, :error_char, :errors, :escape, :euid, :euid=, :eval, :even?, :exception, :excl, :exclude_end?, :exclusive, :exec, :exec_format, :exec_name, :executable?, :executable_real?, :executables, :exist?, :exists?, :exit, :exit!, :exit_code, :exit_value, :exited?, :exitstatus, :exp, :expand, :expand_path, :extend, :extend_object, :extended, :extensions, :external_encoding, :extname, :f, :fail, :fallback, :fatal, :fcntl, :fdatasync, :fdiv, :feed, :fetch, :fetch_spec, :fetcher, :file, :file?, :file_path, :filename, :fileno, :files, :fill, :find, :find_all, :find_all_by_name, :find_by_name, :find_by_path, :find_files, :find_home, :find_in_unresolved, :find_in_unresolved_tree, :find_index, :find_matching, :finish, :finished, :finite?, :first, :fixed_encoding?, :flat_map, :flatten, :flatten!, :flock, :floor, :flush, :fnmatch, :fnmatch?, :for_fd, :force_encoding, :foreach, :fork, :format, :found_spec, :found_specs, :freeze, :frexp, :friday?, :frozen?, :fsync, :ftype, :full_gem_path, :gamma, :garbage_collect, :gcd, :gcdlcm, :gem, :gem_installer, :gem_name, :gem_original_require, :gem_preluded, :gemdir, :gemname, :getbyte, :getc, :getegid, :geteuid, :getgid, :getgm, :getlocal, :getpgid, :getpgrp, :getpriority, :getrlimit, :gets, :getuid, :getutc, :getwd, :gid, :gid=, :glob, :global_variables, :globbed, :gm, :gmt?, :gmt_offset, :gmtime, :gmtoff, :gp, :grant_privilege, :grep, :group, :group_by, :groups, :groups=, :grpowned?, :gsub, :gsub!, :gunzip, :gzip, :h, :has_key?, :has_value?, :hash, :have_tools, :hex, :home, :hook, :host, :host=, :hour, :hypot, :i, :id2name, :identical?, :imag, :imaginary, :include, :include?, :included, :included_modules, :incomplete_input, :incomplete_input?, :index, :infinite?, :inflate, :inherited, :init, :initgroups, :initialize, :initialize_clone, :initialize_copy, :initialize_dup, :inject, :ino, :inplace_mode, :inplace_mode=, :insert, :insert_output, :inspect, :install_dir, :instance_eval, :instance_exec, :instance_method, :instance_methods, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :integer?, :intern, :internal_encoding, :invalid, :invalid_byte_sequence, :invert, :io, :ioctl, :is_a?, :isatty, :isdst, :issetugid, :iterator?, :join, :k, :keep_if, :key, :key?, :keys, :kill, :kind_of?, :klass, :lambda, :lambda?, :last, :last_error, :last_gem_path, :last_match, :latest, :latest_load_paths, :latest_partials, :latest_rubygems_version, :latest_spec_for, :latest_version_for, :lchmod, :lchown, :lcm, :ldexp, :left, :length, :lgamma, :libdir, :libfile, :lineno, :lineno=, :lines, :link, :list, :ljust, :load, :load_env_plugins, :load_error, :load_path, :load_path_file, :load_path_insert_index, :load_plugin_files, :load_plugins, :load_yaml, :loaded_path?, :loaded_specs, :local, :local_variables, :locale_charmap, :localtime, :location_of_caller, :lock, :locked?, :log, :log10, :log2, :loop, :lstat, :lstrip, :lstrip!, :magnitude, :main, :map, :map!, :marshal_dump, :marshal_load, :marshal_version, :match, :matches, :matches_for_glob, :matching_specs, :max, :max_by, :maxgroups, :maxgroups=, :mday, :member?, :members, :merge, :merge!, :mesg, :message, :method, :method_added, :method_defined?, :method_missing, :method_removed, :method_undefined, :methods, :min, :min_by, :minmax, :minmax_by, :mkdir, :mkdir_p, :mktime, :mode, :module_eval, :module_exec, :module_function, :modulo, :mon, :monday?, :month, :msg, :mtime, :n, :name, :name_list, :named_captures, :names, :nan?, :nano_den, :nano_num, :nesting, :new, :new_seed, :new_sources, :newval, :next, :next!, :next_values, :nil?, :nlink, :none, :none?, :nonzero?, :noreuse, :normal, :now, :nsec, :numerator, :object_id, :oct, :odd?, :offset, :old, :old_umask, :one?, :open, :open_args, :options, :ord, :original, :over, :over_name, :over_paths, :owned?, :owner, :p, :pack, :package_name, :parameters, :partial_input, :partials, :partition, :pass, :pat, :path, :path_to_full_rubygems_library, :paths, :paths=, :peek, :peek_values, :perm, :permutation, :phase, :pid, :pipe, :pipe?, :platforms, :platforms=, :plugin, :plugins, :polar, :pop, :popen, :pos, :pos=, :post_build, :post_build_hooks, :post_install, :post_install_hooks, :post_match, :post_reset, :post_reset_hooks, :post_uninstall, :post_uninstall_hooks, :ppid, :pre_install, :pre_install_hooks, :pre_match, :pre_reset, :pre_reset_hooks, :pre_uninstall, :pre_uninstall_hooks, :pred, :prefix, :prepend, :primitive_convert, :primitive_errinfo, :print, :printf, :priority, :priority=, :private, :private_class_method, :private_constant, :private_instance_methods, :private_method_defined?, :private_methods, :proc, :product, :promote_load_path, :protected, :protected_instance_methods, :protected_method_defined?, :protected_methods, :public, :public_class_method, :public_constant, :public_instance_method, :public_instance_methods, :public_method, :public_method_defined?, :public_methods, :public_send, :push, :putback, :putc, :puts, :pwd, :quo, :quote, :r, :raise, :rand, :random, :rassoc, :rationalize, :rdev, :rdev_major, :rdev_minor, :re_exchange, :re_exchangeable?, :read, :read_binary, :read_nonblock, :readable?, :readable_real?, :readagain_bytes, :readbyte, :readchar, :readline, :readlines, :readlink, :readpartial, :real, :real?, :realdirpath, :realpath, :reason, :receiver, :rect, :rectangular, :reduce, :refresh, :regexp, :rehash, :reject, :reject!, :remainder, :remove, :remove_class_variable, :remove_const, :remove_instance_variable, :remove_method, :rename, :reopen, :repeated_combination, :repeated_permutation, :repl, :replace, :replacement, :replacement=, :replicate, :report, :report_activate_error, :require, :require_paths, :require_relative, :required_location, :requirement, :requirements, :reset, :resolving, :respond_to?, :respond_to_missing?, :restore, :result, :resume, :reverse, :reverse!, :reverse_each, :rewind, :rid, :rindex, :rjust, :rmdir, :rotate, :rotate!, :round, :rp, :rpartition, :rstrip, :rstrip!, :ruby, :ruby_engine, :ruby_install_name, :ruby_version, :rubylibprefix, :run, :s, :safe_level, :sample, :saturday?, :say, :scan, :search_convpath, :searcher, :sec, :seed, :seek, :select, :select!, :self, :send, :sequential, :set_backtrace, :set_encoding, :set_trace_func, :setbyte, :setegid, :seteuid, :setgid, :setgid?, :setpgid, :setpgrp, :setpriority, :setregid, :setresgid, :setresuid, :setreuid, :setrgid, :setrlimit, :setruid, :setsid, :setuid, :setuid?, :shift, :shuffle, :shuffle!, :sid_available?, :signaled?, :signm, :signo, :sin, :singleton_class, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined, :singleton_methods, :singletonclass, :sinh, :sitedir, :sitelibdir, :size, :size?, :skip, :skip=, :skip_during, :skip_list, :sleep, :slice, :slice!, :slice_before, :socket?, :sort, :sort!, :sort_by, :sort_by!, :source, :source_buffer_empty, :source_encoding, :source_encoding_name, :source_index, :source_location, :sources, :sources=, :spawn, :spec, :spec_tuples, :specfn, :specs, :split, :sprintf, :sqrt, :squeeze, :squeeze!, :srand, :start, :start_with?, :stat, :state, :status, :step, :sticky?, :stime, :stop, :stop?, :stopped?, :stopsig, :store, :stress, :stress=, :strftime, :string, :strip, :strip!, :sub, :sub!, :subdir, :submicro, :subsec, :succ, :succ!, :success?, :suffix_pattern, :suffixes, :sum, :sunday?, :superclass, :swapcase, :swapcase!, :switch, :symlink, :symlink?, :sync, :sync=, :synchronize, :syscall, :sysopen, :sysread, :sysseek, :system, :syswrite, :t, :taint, :tainted?, :take, :take_while, :tan, :tanh, :tap, :target, :tell, :terminate, :termsig, :test, :text, :textmode, :throw, :thursday?, :time, :times, :to_a, :to_ary, :to_c, :to_enum, :to_f, :to_hash, :to_i, :to_int, :to_io, :to_path, :to_proc, :to_r, :to_s, :to_spec, :to_str, :to_sym, :to_write_io, :total_time, :tr, :tr!, :tr_s, :tr_s!, :trace_var, :transpose, :trap, :truncate, :trust, :try_activate, :try_convert, :try_lock, :tty?, :tuesday?, :tv_nsec, :tv_sec, :tv_usec, :ui, :uid, :uid=, :umask, :unbind, :undef, :undef_method, :undefine_finalizer, :undefined_conversion, :ungetbyte, :ungetc, :union, :uniq, :uniq!, :universal_newline, :unlink, :unlock, :unpack, :unresolved_deps, :unshift, :untaint, :untrace_var, :untrust, :untrusted?, :upcase, :upcase!, :update, :upto, :use_paths, :usec, :user_dir, :user_home, :utc, :utc?, :utc_offset, :utime, :v, :val, :valid_encoding?, :value, :value?, :values, :values_at, :var, :ver, :verbose, :version, :wait, :wait2, :waitall, :waitpid, :waitpid2, :wakeup, :warn, :wday, :wednesday?, :width, :willneed, :win_platform?, :windows, :with_index, :with_object, :world_readable?, :world_writable?, :wrap, :writable?, :writable_real?, :write, :write_nonblock, :xml, :yday, :year, :yield, :zero?, :zip, :zipped, :zone, :|, :~]

1.8 的Symbol没有sort方法, 所以需要转换一下.
str_arr = Symbol.all_symbols.collect{ |s| s.to_s }

p( str_arr.sort )

【参考】
The Book Of Ruby
Ruby 1.9.3 API

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
阿里云服务器怎么设置密码?怎么停机?怎么重启服务器?
如果在创建实例时没有设置密码,或者密码丢失,您可以在控制台上重新设置实例的登录密码。本文仅描述如何在 ECS 管理控制台上修改实例登录密码。
4072 0
使用NAT网关轻松为单台云服务器设置多个公网IP
在应用中,有时会遇到用户询问如何使单台云服务器具备多个公网IP的问题。 具体如何操作呢,有了NAT网关这个也不是难题。
22600 0
怎么设置阿里云服务器安全组?阿里云安全组规则详细解说
阿里云服务器安全组设置规则分享,阿里云服务器安全组如何放行端口设置教程
6936 0
阿里云服务器端口号设置
阿里云服务器初级使用者可能面临的问题之一. 使用tomcat或者其他服务器软件设置端口号后,比如 一些不是默认的, mysql的 3306, mssql的1433,有时候打不开网页, 原因是没有在ecs安全组去设置这个端口号. 解决: 点击ecs下网络和安全下的安全组 在弹出的安全组中,如果没有就新建安全组,然后点击配置规则 最后如上图点击添加...或快速创建.   have fun!  将编程看作是一门艺术,而不单单是个技术。
4504 0
使用OpenApi弹性释放和设置云服务器ECS释放
云服务器ECS的一个重要特性就是按需创建资源。您可以在业务高峰期按需弹性的自定义规则进行资源创建,在完成业务计算的时候释放资源。本篇将提供几个Tips帮助您更加容易和自动化的完成云服务器的释放和弹性设置。
7772 0
阿里云服务器安全组设置内网互通的方法
虽然0.0.0.0/0使用非常方便,但是发现很多同学使用它来做内网互通,这是有安全风险的,实例有可能会在经典网络被内网IP访问到。下面介绍一下四种安全的内网互联设置方法。 购买前请先:领取阿里云幸运券,有很多优惠,可到下文中领取。
9436 0
阿里云服务器如何登录?阿里云服务器的三种登录方法
购买阿里云ECS云服务器后如何登录?场景不同,阿里云优惠总结大概有三种登录方式: 登录到ECS云服务器控制台 在ECS云服务器控制台用户可以更改密码、更换系.
5730 0
腾讯云服务器 设置ngxin + fastdfs +tomcat 开机自启动
在tomcat中新建一个可以启动的 .sh 脚本文件 /usr/local/tomcat7/bin/ export JAVA_HOME=/usr/local/java/jdk7 export PATH=$JAVA_HOME/bin/:$PATH export CLASSPATH=.
2147 0
+关注
德哥
公益是一辈子的事, I&#39;m digoal, just do it.
2153
文章
245
问答
文章排行榜
最热
最新
相关电子书
更多
文娱运维技术
立即下载
《SaaS模式云原生数据仓库应用场景实践》
立即下载
《看见新力量:二》电子书
立即下载