summaryrefslogtreecommitdiff
path: root/doc/syntax/literals.rdoc
blob: e01b6875d4239dd10783f794d5cc81c562005e81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
= Literals

Literals create objects you can use in your program.  Literals include:

* Booleans and nil
* Numbers
* Strings
* Symbols
* Arrays
* Hashes
* Ranges
* Regular Expressions
* Procs

== Booleans and nil

+nil+ and +false+ are both false values.  +nil+ is sometimes used to indicate
"no value" or "unknown" but evaluates to +false+ in conditional expressions.

+true+ is a true value.  All objects except +nil+ and +false+ evaluate to a
true value in conditional expressions.

(There are also the constants +TRUE+, +FALSE+ and +NIL+, but the lowercase
literal forms are preferred.)

== Numbers

You can write integers of any size as follows:

  1234
  1_234

These numbers have the same value, 1,234.  The underscore may be used to
enhance readability for humans.  You may place an underscore anywhere in the
number.

Floating point numbers may be written as follows:

  12.34
  1234e-2
  1.234E1

These numbers have the same value, 12.34.  You may use underscores in floating
point numbers as well.

You can use a special prefix to write numbers in decimal, hexadecimal, octal
or binary formats.  For decimal numbers use a prefix of <tt>0d</tt>, for
hexadecimal numbers use a prefix of <tt>0x</tt>, for octal numbers use a
prefix of <tt>0</tt> or <tt>0o</tt>, for binary numbers use a prefix of
<tt>0b</tt>.  The alphabetic component of the number is not case-sensitive.

Examples:

  0d170
  0D170

  0xaa
  0xAa
  0xAA
  0Xaa
  0XAa
  0XaA

  0252
  0o252
  0O252

  0b10101010
  0B10101010

All these numbers have the same decimal value, 170.  Like integers and floats
you may use an underscore for readability.

== Strings

The most common way of writing strings is using <tt>"</tt>:

  "This is a string."

The string may be many lines long.

Any internal <tt>"</tt> must be escaped:

  "This string has a quote: \".  As you can see, it is escaped"

Double-quote strings allow escaped characters such as <tt>\n</tt> for newline,
<tt>\t</tt> for tab, etc.

Double-quote strings allow interpolation of other values using
<tt>#{...}</tt>:

  "One plus one is two: #{1 + 1}"

Any expression may be placed inside the interpolated section, but it's best to
keep the expression small for readability.

Interpolation may be disabled by escaping the "#" character or using
single-quote strings:

  '#{1 + 1}' #=> "\#{1 + 1}"

In addition to disabling interpolation, single-quoted strings also disable all
escape sequences except for the single-quote (<tt>\'</tt>).

You may also create strings using <tt>%</tt>:

  %(1 + 1 is #{1 + 1}) #=> "1 + 1 is 2"

There are two different types of <tt>%</tt> strings <tt>%q(...)</tt> behaves
like a single-quote string (no interpolation or character escaping) while
<tt>%Q</tt> behaves as a double-quote string.  See Percent Strings below for
more discussion of the syntax of percent strings.

Adjacent string literals are automatically concatenated by the interpreter:

  "con" "cat" "en" "at" "ion" #=> "concatenation"
  "This string contains "\
  "no newlines."              #=> "This string contains no newlines."

Any combination of adjacent single-quote, double-quote, percent strings will
be concatenated as long as a percent-string is not last.

  %q{a} 'b' "c" #=> "abc"
  "a" 'b' %q{c} #=> NameError: uninitialized constant q

=== Here Documents

If you are writing a large block of text you may use a "here document" or
"heredoc":

  expected_result = <<HEREDOC
  This would contain specially formatted text.

  That might span many lines
  HEREDOC

The heredoc starts on the line following <tt><<HEREDOC</tt> and ends with the
next line that starts with <tt>HEREDOC</tt>.  The result includes the ending
newline.

You may use any identifier with a heredoc, but all-uppercase identifiers are
typically used.

You may indent the ending identifier if you place a "-" after <tt><<</tt>:

    expected_result = <<-INDENTED_HEREDOC
  This would contain specially formatted text.

  That might span many lines
    INDENTED_HEREDOC

Note that the while the closing identifier may be indented, the content is
always treated as if it is flush left.  If you indent the content those spaces
will appear in the output.

A heredoc allows interpolation and escaped characters.  You may disable
interpolation and escaping by surrounding the opening identifier with single
quotes:

  expected_result = <<-'EXPECTED'
  One plus one is #{1 + 1}
  EXPECTED

  p expected_result # prints: "One plus one is \#{1 + 1}\n"

The identifier may also be surrounded with double quotes (which is the same as
no quotes) or with backticks.  When surrounded by backticks the HEREDOC
behaves like Kernel#`:

  puts <<-`HEREDOC`
  cat #{__FILE__}
  HEREDOC

To call a method on a heredoc place it after the opening identifier:

  expected_result = <<-EXPECTED.chomp
  One plus one is #{1 + 1}
  EXPECTED

You may open multiple heredocs on the same line, but this can be difficult to
read:

  puts(<<-ONE, <<-TWO)
  content for heredoc one
  ONE
  content for heredoc two
  TWO

== Symbols

A Symbol represents a name inside the ruby interpreter.  See Symbol for more
details on what symbols are and when ruby creates them internally.

You may reference a symbol using a colon: <tt>:my_symbol</tt>.

You may also create symbols by interpolation:

  :"my_symbol1"
  :"my_symbol#{1 + 1}"

Note that symbols are never garbage collected so be careful when referencing
symbols using interpolation.

Like strings, a single-quote may be used to disable interpolation:

  :'my_symbol#{1 + 1}' #=> :"my_symbol\#{1 + 1}"

When creating a Hash there is a special syntax for referencing a Symbol as
well.

== Arrays

An array is created using the objects between <tt>[</tt> and <tt>]</tt>:

  [1, 2, 3]

You may place expressions inside the array:

  [1, 1 + 1, 1 + 2]
  [1, [1 + 1, [1 + 2]]]

See Array for the methods you may use with an array.

== Hashes

A hash is created using key-value pairs between <tt>{</tt> and <tt>}</tt>:

  { "a" => 1, "b" => 2 }

Both the key and value may be any object.

You can create a hash using symbol keys with the following syntax:

  { a: 1, b: 2 }

This same syntax is used for keyword arguments for a method.

See Hash for the methods you may use with a hash.

== Ranges

A range represents an interval of values.  The range may include or exclude
its ending value.

  (1..2)  # includes its ending value
  (1...2) # excludes its ending value

You may create a range of any object.  See the Range documentation for details
on the methods you need to implement.

== Regular Expressions

A regular expression is created using "/":

  /my regular expression/

The regular expression may be followed by flags which adjust the matching
behavior of the regular expression.  The "i" flag makes the regular expression
case-insensitive:

  /my regular expression/i

Interpolation may be used inside regular expressions along with escaped
characters.  Note that a regular expression may require additional escaped
characters than a string.

See Regexp for a description of the syntax of regular expressions.

== Procs

A proc can be created with <tt>-></tt>:

  -> { 1 + 1 }

Calling the above proc will give a result of <tt>2</tt>.

You can require arguments for the proc as follows:

  ->(v) { 1 + v }

This proc will add one to its argument.

== Percent Strings

Besides <tt>%(...)</tt> which creates a String, The <tt>%</tt> may create
other types of object.  As with strings, an uppercase letter allows
interpolation and escaped characters while a lowercase letter disables them.

These are the types of percent strings in ruby:

<tt>%i</tt> :: Array of Symbols
<tt>%q</tt> :: String
<tt>%r</tt> :: Regular Expression
<tt>%s</tt> :: Symbol
<tt>%w</tt> :: Array of Strings
<tt>%x</tt> :: Backtick (capture subshell result)

For the two array forms of percent string, if you wish to include a space in
one of the array entries you must escape it with a "\\" character:

  %w[one one-hundred\ one]
  #=> ["one", "one-hundred one"]

If you are using "(", "[", "{", "<" you must close it with ")", "]", "}", ">"
respectively.  You may use most other non-alphanumeric characters for percent
string delimiters such as "%", "|", "^", etc.