O'Reilly logo

Ruby in a Nutshell by Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Literals

I've often wondered why we programmers are so enamored with literals. I'm waiting for the day when a language comes along and introduces "figuratives." In the interim, the rules Ruby uses for literals are simple and intuitive, as you'll see the following sections.

Numbers

Strings and numbers are the bread and butter of literals. Ruby provides support for both integers and floating-point numbers, using classes Fixnum, Bignum, and Float.

Integers

Integers are instances of class Fixnum or Bignum:

123                    # decimal
1_234                  # decimal with underline 
0377                   # octal
0xff                   # hexadecimal
0b1011                 # binary
?a                     # character code for 'a'
12345678901234567890   # Bignum:  an integer of infinite length

Floating-point numbers

Floating-point numbers are instances of class Float:

123.4                    # floating point value
1.0e6                    # scientific notation
4E20                     # dot not required
4e+20                    # sign before exponential

Strings

A string is an array of bytes (octets) and an instance of class String:

"abc"

Double-quoted strings allow substitution and backslash notation.

'abc'

Single-quoted strings don't allow substitution and allow backslash notation only for \\ and \'.

String concatenation

Adjacent strings are concatenated at the same time Ruby parses the program.

"foo" "bar"           # means "foobar"

Expression substitution

#$var and #@var are abbreviated forms of #{$var} and #{@var}. Embeds value of expression in #{...} into a string.

Backslash notation

In double-quoted strings, regular expression literals, and command output, backslash notation can be ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required