What does the “$” character mean in Ruby?

前端 未结 5 1634
深忆病人
深忆病人 2020-12-08 01:40

Been playing with Ruby on Rails for awhile and decided to take a look through the actual source. Grabbed the repo from GitHub and started looking around. Came across some co

相关标签:
5条回答
  • 2020-12-08 02:14

    $ identifies a global variable, as opposed to a local variable, @instance variable, or @@class variable.

    Among the language-supplied global variables are $:, which is also identified by $LOAD_PATH

    0 讨论(0)
  • 2020-12-08 02:21

    I wanna note something weird about Ruby!

    $ does indeed mean load path. And ; means "end line". But!

    $; means field separator. Try running $;.to_s in your REPL and you'll see it return ",". That's not all! $ with other suffixes can mean many other things.

    Why? Well, Perl of course!

    0 讨论(0)
  • 2020-12-08 02:26
    $:.unshift
    

    is the same as

    $LOAD_PATH.unshift
    

    . You can also say:

    $: <<
    $LOAD_PATH <<
    

    They are pretty common Ruby idioms to set a load path.

    0 讨论(0)
  • 2020-12-08 02:36

    To quote the Ruby Forum:

    ruby comes with a set of predefined variables

    $: = default search path (array of paths)
    __FILE__ = current sourcefile
    

    if i get it right (not 100% sure) this adds the lib path to this array of search paths by going over the current file. which is not exactly the best way, i would simply start with RAILS_ROOT (at least for a rails project)

    0 讨论(0)
  • 2020-12-08 02:39

    $: is the global variable used for looking up external files.

    From http://www.zenspider.com/Languages/Ruby/QuickRef.html#18

    $: Load path for scripts and binary modules by load or require.

    0 讨论(0)
提交回复
热议问题