Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Ruby Programming/Syntax/Variables and Constants

From Wikibooks, open books for an open world
<Ruby Programming |Syntax

A variable in Ruby can be distinguished by the characters at the start of its name. There's no restriction to the length of a variable's name (with the exception of the heap size).

Summary

[edit |edit source]

The first character indicates the scope:

  • Local variables - lowercase letter or underscore
  • Instance variables - @
    • In class scope, instance variables belong to the object thatis the class
    • To define instance variables on the objects thatbelong to the class, use @ inside initialize()
  • Class variables - @@
  • Global variables - $
  • Constants - uppercase letter

For more information on variable scopes related to classes, seeRuby Programming/Syntax/Classes.

Local Variables

[edit |edit source]

Example:

foobar_foobar

A variable whose name begins with a lowercase letter (a-z) or underscore (_) is a local variable or method invocation.

A local variable is only accessible from within the block of its initialization. For example:

i0 = 1loop {  i1 = 2  puts defined?(i0)# true; "i0" was initialized in the ascendant block  puts defined?(i1)# true; "i1" was initialized in this block  break}puts defined?(i0)# true; "i0 was initialized in this blockputs defined?(i1)# false; "i1" was initialized in the loop

Instance Variables

[edit |edit source]

Example:

@foobar

A variable whose name begins with '' is an instance variable of . An instance variable belongs to theobject itself. Uninitialized instance variables have a value of .

Class Variables

[edit |edit source]

A class variable is shared by all instances of a class and begins with '@@'.Example:

@@foobar

An important note is that the class variable is shared by all the descendants of the class.Example:

classParent@@foo="Parent"endclassThing1<Parent@@foo="Thing1"endclassThing2<Parent@@foo="Thing2"end>>Parent.class_eval("@@foo")=>"Thing2">>Thing1.class_eval("@@foo")=>"Thing2">>Thing2.class_eval("@@foo")=>"Thing2">>Thing2.class_variables=>[]Parent.class_variables=>[:@@foo]

This shows us that all our classes were changing the same variable. Class variables behave like global variables which are visible only in the inheritance tree. Because Ruby resolves variables by looking up the inheritance tree *first*, this can cause problems if two subclasses both add a class variable with the same name.

Global Variables

[edit |edit source]

Example:

$foobar

A variable whose name begins with '' has a global scope; meaning it can be accessed from anywhere within the program during runtime.

Constants

[edit |edit source]

Usage:

FOOBAR

A variable whose name begins with an uppercase letter (A-Z) is a constant. A constant can be reassigned a value after its initialization, but doing so will generate a warning. Everyclass is a constant.

Trying to access an uninitialized constant raises the NameError exception.

How constants are looked up

[edit |edit source]

Constants are looked up based on your scope or via the scope resolution operator (i.e. '::').For example

 class A   A2 = 'a2'   class B     def go       A2      end   end end instance_of_b = A::B.new a2 = A::A2

Another example

class Foo  BAR = 123endputs Foo::BAR   # => 123

Pseudo Variables

[edit |edit source]

self

Execution context of the current method, which could refer to an instance, class, or module.

nil

The sole-instance of theNilClass class. Expresses nothing.

true

The sole-instance of theTrueClass class. Expresses true.

false

The sole-instance of theFalseClass class. Expresses false.

$1, $2 ... $9

These are contents of capturing groups for regular expression matches. They are local to thecurrent thread and stack frame!

(nil also is considered to befalse, and every other value is considered to betrue in Ruby.)The value of a pseudo variable cannot be changed. Substitution to a pseudo variable causes an exception to be raised.

Pre-defined Variables

[edit |edit source]

Many pre-defined variables are useful when dealing with regular expressions or Ruby interpreter parameters.

NameAliasesDescription
$!$ERROR_INFO[1]The exception information message set by the last 'raise' (last exception thrown).
$@$ERROR_POSITION[1]Array of the backtrace of the last exception thrown.
$&$MATCH[1]The string matched by the last successful pattern match in this scope.
$`$PREMATCH[1]The string to the left of the last successful match.
$'$POSTMATCH[1]The string to the right of the last successful match.
$+$LAST_PAREN_MATCH[1]The last group of the last successful match.
$1 to$9The Nth group of the last successful regexp match.
$~$LAST_MATCH_INFO[1]The information about the last match in the current scope.
$=$IGNORECASE[1]The flag for case insensitive, nil by default (deprecated).
$/$INPUT_RECORD_SEPARATOR[1],$RS[1] or$-0The input record separator, newline by default.
$\$OUTPUT_RECORD_SEPARATOR[1] or$ORS[1]The output record separator for the print and IO#write. Default is nil.
$,$OUTPUT_FIELD_SEPARATOR[1] or$OFS[1]The output field separator for the print and Array#join.
$;$FIELD_SEPARATOR[1],$FS[1] or$-FThe default separator for String#split.
$.$INPUT_LINE_NUMBER[1] or$NR[1]The current input line number of the last file that was read.
$<$DEFAULT_INPUT[1]An object that provides access to the concatenation of the contents of all the files given as command-line arguments, or $stdin (in the case where there are no arguments). Read only.
$FILENAMECurrent input file from $<. Same as $<.filename.
$>$DEFAULT_OUTPUT[1]The destination of output for Kernel.print and Kernel.printf. The default value is $stdout.
$_$LAST_READ_LINE[1]The last input line of string by gets or readline.
$0Contains the name of the script being executed. May be assignable.
$*ARGV[1]Command line arguments given for the script. Also known asARGV
$$$PROCESS_ID[1],$PID[1] orProcess.pidThe process number of the Ruby running this script.
$?$CHILD_STATUS[1]The status of the last executed child process.
$:$LOAD_PATHLoad path for scripts and binary modules by load or require.
$"$LOADED_FEATURES or$-IThe array contains the module names loaded by require.
$stderrThe current standard error output.
$stdinThe current standard input.
$stdoutThe current standard output.
$-d$DEBUGThe status of the -d switch. Assignable.
$-K$KCODECharacter encoding of the source code.
$-v$VERBOSEThe verbose flag, which is set by the -v switch.
$-aTrue if option -a ("autosplit" mode) is set. Read-only variable.
$-iIf in-place-edit mode is set, this variable holds the extension, otherwise nil.
$-lTrue if option -l is set ("line-ending processing" is on). Read-only variable.
$-pTrue if option -p is set ("loop" mode is on). Read-only variable.
$-wTrue if option -w is set.

To avoid the criticism that two-character, punctuation-based variable names are cryptic or confusing, part of the standard library is "English" which defines the longer names listed in the table above. To include these names, just require the English library as follows.[1]

Without ‘English’:

   $\ = ' -- '   "waterbuffalo" =~ /buff/   print $", $', $$, "\n"

With English:

   require "English"      $OUTPUT_FIELD_SEPARATOR = ' -- '   "waterbuffalo" =~ /buff/   print $LOADED_FEATURES, $POSTMATCH, $PID, "\n"

Pre-defined Constants

[edit |edit source]

Note that there are some pre-defined constants at parse time, as well, namely

 __FILE__   (current file) __LINE__   (current line)

and

 __dir__    (current directory) __method__ (current method)

(new in Ruby 2.0)

Alist of predefined global constants can be found in the Ruby language documentation.[2] Among the notable ones are:

Global constant nameDescription
STDINThe standard input. The default value for$stdin.
STDOUTThe standard output. The default value for$stdout.
STDERRThe standard error output. The default value for$stderr.
ENVThe hash contains current environment variables.
ARGVAn Array of command line arguments given for the script.
RUBY_VERSIONThe Ruby language version,e.g.,ruby -e 'puts RUBY_VERSION' will print2.7.0.
RUBY_RELEASE_DATEThe release date string,e.g.,2019-12-25.
RUBY_PLATFORMThe platform identifier,e.g.,x86_64-linux-gnu
RUBY_PATCHLEVELThe patchlevel for this Ruby,e.g.,0. If this is a development build of Ruby the patchlevel will be-1.

Notes

[edit |edit source]
  1. abcdefghijklmnopqrstuvwxyzEnglish.rb from theRuby 1.9.2 Standard Library Documentation
  2. The document onpre-defined global variables and constants from the official Ruby documentation
Previous: LexicologyIndexNext: Literals
Retrieved from "https://en.wikibooks.org/w/index.php?title=Ruby_Programming/Syntax/Variables_and_Constants&oldid=4341769"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp