-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathRuby Notes
More file actions
1754 lines (1250 loc) · 67.4 KB
/
Ruby Notes
File metadata and controls
1754 lines (1250 loc) · 67.4 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Ruby Notes
Ruby is interpreted. Ruby is a server-side scripting language simliar to Python and Perl.
Ruby can be embedded into HTML.
Ruby supports GUI tools such as Tcl/Tk, GTC, and OpenGL.
Ruby is considered a perfect OOP language.
************************ GENERAL RUBY NOTES ************************
irb:
You can type irb into the command line to bring up the Interactive Ruby (IRb), which is the
Ruby shell for Ruby experimentation.
All Ruby files have the following file extension: .rb
For linux at the beginning of the source code put: #!/usr/bin/ruby -w
The "-w" option enables warnings to be used when whitespace is sometimes used to interpret ambiguous
statements. Normally whitespace is ignored in Ruby code though.
i.e. a + b is interpreted as a+b <-- a local variable
a +b is interpreted as a(+b) <-- a method call
Run programs on the command line like so: ruby filename.rb
************************ GENERAL SYNTAX ************************
Line Endings:
Ruby interprets semi-colons and newline characters (by newline characters this means nothing
at the end of a statement) as the ending of a statement.
If Ruby encounters operators, like +,-, or \ at the end of a line it acts as a continuation
character to continue the statement onto the next line.
Comments:
Use # for comments.
Like other scripting languages, # works the same way that // works in C++
Create a block comment as follows, using =begin and =end:
=begin
This is a block comment
And it is three whole
lines
long!
=end
Ruby identifiers/keywords are case sensitive.
Ruby keywords:
BEGIN
END
alias
and
begin
break
case
class
def
defined?
do
else
elsif
end
ensure
false
for
if
in
module
next
nil
not
or
redo
rescue
retry
return
self
super
then
true
undef
unless
until
when
while
__FILE__
__LINE__
Here Document:
Basically a Here Document is a way to build strings that are multiple lines. You create it by
using a << followed immediately by either a string literal or an identifier used to terminate
the here document (the multi-line string). All the lines following the line with <<, up to the
terminator, are the value of the string.
The terminator, if used, can be without quotes or with quotes, and if with quotes then the type
of quotes matters. Double quotes is the same as not using quotes, and this just creates a string
literal. But single quotes treats the multi-line string as Ruby code commands to execute.
i.e.
print <<EOF
This is the first line of a here document multi-line string,
and this is the second.
EOF
print <<"EOF"
This is the same as the above here document
because double-quotes is same as no quotes around terminator.
print <<'EOC'
echo this will print out everything but echo
echo because echo is a keyword to print like in php.
EOC
print <<"firstTerminator", <<"secondTerminator"
This will print out for the first here document.
firstTerminator
This will print out for the second here document.
secondTerminator
BEGIN:
Syntax: BEGIN {
code...
}
The BEGIN keyword is used to contain the code that will be run before the program is run.
i.e.
#!/usr/bin/ruby
puts "this is the main program"
BEGIN {
puts "Initializing the Ruby program"
}
END:
Syntax: END {
code...
}
The END keyword declares code to be called at the end of the program.
i.e.
#!/usr/bin/ruby
puts "This is the main program"
END {
puts "Terminating the program"
}
BEGIN {
puts "Initializing the program"
}
************************ CLASSES AND OBJECTS ************************
To define a class in Ruby start with the "class" keyword, then the class name which should have an
uppercase first letter, and you end a class definition with the "end" keyword.
Syntax: class MyClass
# class definition...
end
Ruby has four types of variables:
Local variables - defined in a method. Starts with a lowercase letter or underscore.
Instance variables - available across any methods in an object (normal member variables of
objects). Use the @ sign to refer to an instance variable
Class variables - available across all objects of a class. Use @@ to refer to a call variable.
Global variables - available across all classes, so available anywhere in the program. Use the
$ sign to refer to a global variable.
Creating Objects:
Use the "new" method of a class to create an object of that class.
i.e.
myObj = MyClass.new
You can create a constructor to pass arguments through the "new" method to the object by using
the "initialize" method in the class definition. You define methods using the "def" keyword, and
ending the method with the "end" keyword.
i.e.
class MyClass
def initialize(var1, var2, var3) # these are local variables
@var1 = var1 # these are instance variables
@var2 = var2
@var3 = var3
end
end
myObj = MyClass.new("blah", 43, "bloop") # creates new object using constructor above
Member Methods:
In Ruby functions are called methods. Each method in a class starts with the "def" keyword and
ends with the "end" keyword. Method names should be lowercase.
i.e. (method to go inside a class)
def function
# code...
end
Note that if a method has no parameters you don't even need to include the paranetheses.
************************ VARIABLES ************************
There are five kinds of variables in Ruby.
Also mentioned some stuff about variables in the above section.
NOTE: You can access the value of any variable or constant, regardless of scope, by putting a
hash (#) character just before it.
Global variables begin with $. Uninitialized global variables have the value nil and produce
warnings with the -w option. It is not recommended to use global variables.
i.e. $globalVar
Instance variables are member variables of an object. Initialized with a @ before the variables
name. Uninitialized global variables have the value nil and produce
warnings with the -w option.
i.e. @instanceVar
Class variables begin with @@. They are shared among all objects and descendents of that class. An example would be a counter that keeps track of how many times that class, and its descendents, have
been instantiated. Overriding class variables produce warnings with the -w option.
i.e. @@classVar
Local variables have no special character to begin with, just a lowercase letter or underscore.
These variables are local to the method, class module, or block from which they originate. When an
uninitialized local variable is referenced it is interpreted as a call to a method that has no
arguments. Assignment to unitialized local variables also serves as variable declaration, so they
have the scope of where they were initialized from.
i.e. localVar
Constants start with an uppercase letter (and generally are entirely uppercase). They can be declared
outside a class or module and have global scope, or inside a class or module and have that scope.
Constants cannot be defined within methods. Referencing an uninitialized constant produces an error,
and making an assignment to a constant that is already initialized produces a warning.
i.e. CONSTANT
Pseudo-Variables:
These are special variables that have the appearance of local variables but behave like
constants. You cannot assign any value to these variables. They are as follows:
self - the receiver object of the current method
true - value representing true
false - value representing false
nil - value representing undefined (null)
__FILE__ - the name of the current source file
__LINE__ - the current line number in the source file
Variable Data Types (Literals):
Integer Numbers:
An integer can range in size from -2^30 to (2^30)-1 or -2^62 to (2^62)-1. Integers in these
ranges are objects of the class "Fixnum". Integers outside this range are stored in objects
of the class "Bignum".
use 0 to start an octal number, 0x to start a hex number, or 0b to start a binary number.
Underscore characters can be written into the integer as they are ignored.
Can get the integer value for an ASCII number or escape sequence by preceding the number
with a question mark:
?a ?\n
Floating-Point Numbers:
Floating-Point numbers are objects of the class "Float" and can take the following forms:
123.4 # normal decimal
1.2e9 # scientific notation
4E9 # scientific notation (don't need a dot and decimal place)
5e+20 # sign (pos or neg) before exponential
String Literals:
String literals are objects of the "String" class. Double-quoted strings allow substitution
and backslash (escape sequence) notation, but single-quoted strings don't allow substitution
and only allow backslash (escape sequence) notation for \\ and \'.
i.e. puts 'escape using "\\"' # output: escape using "\""
puts 'That\'s right' # output: That's right
To substitute the value of any Ruby expression into a string use the following format:
#{expr}
i.e.
puts "Value: #{11.4*150}"
Escape Characters:
\n
\r - carriage return
\f - form feed
\b - backspace
\a - alert
\e - escape
\s - space
\nnn - octal notation
\xnn - hex notation
\cx, \C-x - Control-x
\M-x - Meta-x
\M-\C-x - Meta-Control-x
\x - Character x
Arrays:
An array in Ruby can hold values of different data types. Create an array with a
comma-separated series of object references (remember everything is an object so all values
and variable types are objects) between square brackets. A trailing comma is ignored.
i.e.
myArray = ["todd", 20, "Blah", 'yo', 2.17]
Hashes:
A literal Hash is created by placing a list of key/value pairs between curly braces, with
either a comma or the sequence => between they key and value. A trailing comma is ignored.
i.e.
myHash = {"todd" => 30, "Deep" => "baby", "Bryce" => "flake", "Pi" => 3.14}
Ranges:
A range represents an interval of a set of values with a start and an end. Ranges may be
constructed using the s..e and s...e literals, or with Range.new.
Ranges constructed with ".." run from the start to the end inclusively, while using "..."
excludes the end value. Range.new() is the same as using "..", so inclusive. When used as an
iterator, ranges return each value in the sequence.
i.e.
1..4 # range is 1,2,3,4
1...4 # range is 1,2,3
Range.new(1,4) # range is 1,2,3,4
************************ OPERATORS ************************
Most operators in Ruby are actually method calls (a + b is interpreted as a.+(b), where the + method
is called by "a" with argument "b".).
For every operator there is a corresonding form of abbreviated assignment operator (i.e. +=).
Arithmetic operators:
+ - * / % **
Comparison operators:
== != > < >= <=
<==> # combines comparison operator, returns 0 if first operand equals
the second, returns 1 if first operand is greater than the
second, returns -1 if first operand is less than the second.
=== # used to test equality within a "when" clause of a case
statement. i.e. (1...10) === 5 returns true
.eql? # true if receiver and argument have both the same type and
equal values (so like === in some other languages).
i.e. 1.eql?(1.0) returns false
.equal? # true if receiver and argument have the same object id, so must
be not just an equal object but actually the same object to
be true.
i.e. if aObj is a duplicate of bObj then aObj==bObj, while
aObj.equal?bObj is false but aObj.equal?aObj is true.
Assignment operators:
= += -= *= /= %= **= |= &= >>= <<= &&= ||= {
Parallel Assignment:
Ruby supports the parallel assignment of variables, which means multiple variables can be
initialized on a single line.
i.e. a, b, c = 10, 20, 30
i.e. a, b = b, c
Bitwise operators:
Works on bits and performs bit by bit operations.
& - and
| - or
^ - xor
~ - one's complement, is unary and has the effect of flipping the bits. i.e. (~60) = -61
<< - binary left shift, the left operands values is moved by the number of bits specified
in the right operand. i.e. 60 << 2 will give 240 (1111 0000)
>> - binary right shift, works the same as the binary left shift operator, but opposite.
Logical operators:
and && or || not ! # can use either version of each operator
NOTE: There is a difference between "and" and &&, as well as between "or" and ||.
See the following website for what the difference is:
http://stackoverflow.com/questions/1426826/difference-between-and-and-in-ruby
Ternary operator:
The ternary operator is a short hand for an if-else statement. Operator is "? :"
i.e. (x == 10) ? x++ : x-- equivalent to: if (x==10)
x++
else
x--
Range operators:
Sequence ranges in Ruby are used to create a range of successive values consisting of a start
value, and end value, and a range of values in between.
The operators, mentioned above in the Variables section are;
.. - creates an inclusive range
... - creates a range inclusive of start value but exclusive of end value
defined? operators:
defined? is a special operator that takes the form of a method call to determine whether or not
the passed expression is defined. It returns a description string of the expression, or nil if
the expression isn't defined.
Syntax: defined? variable # true if variable is initialized
i.e. foo = 43
defined? foo # returns "local-variable"
defined? $_ # returns "global-variable"
defined? bar # returns nil if undefined
Syntax: defined? method_call # true if method is defined
i.e. defined? puts # returns "method"
defined? puts(bar) # nil if bar is undefined
defined? unpack # nil is unpack is undefined
Syntax: defined? super # true if a method exists that can be called with super user
i.e. defined? super # "super" if it can be called
defined? super # "nil" if it cannot be called
Syntax: defined? yield # true if a code black has been passed
i.e. defined? yield # "yield" if there is a block passed
defined? yield # "nil" if there is no block
Dot and Double Colon operators:
Use the Dot operator to call a module method (like most languages), and you can reference a
constantusing the module name and two colons.
The :: is a unary operator that allows constants, instance methods, and class methods defined
within a class or module to be accessed from anywhere outside the class or module.
Remember, in Ruby classes and methods may be considered constants too.
You can prefix the :: operator with an expression that returns the appropriate class or module
object, or if you don't use any prefix for it then the main Object class is used by default.
i.e.
::CONST = 1
ClassName::CONST = 1 # if the constant is in the class "ClassName"
More operators:
[][]= element reference, element set
=~
!~
************************ CONDITIONALS ************************
The three conditional are: if-elsif-else
unless-else
case-when-else
"if" and "unless" can be used as modifiers in the middle of a line of code as well.
if-statement:
In an if-statement, the values "false" and "nil" are false, everything else is true.
At the end of the line of code with the "if" you can either put a semi-colon, the "then" keyword,
or nothing.
Note that the else-if statement in Ruby is: elsif
Note also that you don't need parentheses around the condition.
if condition
# code...
elsif condition
# code...
else
# code...
end
The "if" Modifier:
You can write an if-condition at the end of some code line.
Syntax: code if condition
i.e. puts "todd is great" if x > 30
The "unless" statement:
The "unless" statement is the opposite of the if-statement. It executes a block of code if the
condition is false, and if the condition is true then it executes the code in the block
statement. All the same syntax rules apply to the "unless" statement that apply to if-statements.
Although I don't think there is a elsif equivalent for the unless-statement.
Syntax: unless conditional
# code...
else
# code...
end
The "unless" Modifier:
Just like with "if", you can use "unless" at the end of some code.
Syntax: code unless condition
i.e. puts "todd is great" unless x < 30
The "case" statement:
Compares the expression specified by case against the expressions in the "when" statements.
The comparison between the case expression and the 'when' expressions uses a hidden === sign.
Just like with if and unless statements, the case and when statements can be ended with a
semi-colon, the keyword "then", or nothing (just an endline). Use the else statement as the
equivalent of default for switch statements in other languages. Putting a comma between values
in the when-statement creates an OR operator so you can test against multiple values, for a
given block to execute.
You can use ranges as the expressions, like 1..5
You can separate the When condition from the code the "then" keyword, nothing (a newline), or
either a semi-colon or colon - I'm not sure, it's either one of these or both.
Syntax: case exp1
when exp2, exp3
# code...
when exp4
# code...
else
# code...
end
************************ LOOPS ************************
Ruby has the following loops: while
for
until
redo
entry
Also the following loops can be used as modifiers occuring in the middle of a line of code:
while
Just like with conditional statements, notice that loop in Ruby don't use parentheses around
conditions.
While-loop:
A while-conditional line can end with either a semi-colon, backslash, the keyword "do", or
nothing (just and endline).
Syntax: while condition
# code...
end
While Modifier:
Syntax: code while condition or use begin
# code...
end while condition
If used in the "code while condition" format it executes as a normal while-loop, that is it
checks the condition first. If using the "begin" keyword with while (with no rescue or ensure
clauses) it creates the equivalent to a do-while loop.
Until-loop:
The opposite of a while-loop, equivalent to an "unless" version of the while-loop.
executes code while the condition is false.
Same syntax rules that apply to a while-loop apply to an until-loop, except in an until-loop
you cannot end the conditional line of code with a backslash.
Syntax: until condition
# code...
end
Until Modifier:
Syntax: code unless condition or use begin
# code...
end until condition
Just like with the 'while' modifier, if using the 'begin' keyword with the until-modifier, if
it doesn't include a rescue or ensure clause then it acts as a do-until loop where the code
executes once before checking the condition.
For-loop:
There is no standard tri-statement for-loop in Ruby.
The only for-loop in ruby is a for-in loop. You set a variable (or multiple variables separated
by commas) to iterate over a range or some set of values.
You can end the conditional statement in the for-loop with a semi-colon, the "do" keyword, or
nothing (just an endline).
Syntax: for variable[,variable...] in expression
# code...
end
i.e. for i in 0..5
puts "Value of local variable is #{i}"
end
Each-do:
".each do" is almost the same as a for-in loop, except that a for-loop doesn't create a new
scope for local variables.
"each" operates on an expression using the dot operator, and then "do" specifies the variable(s)
to use to iterate through the expression, as well as the code to be executed for each element of
the expression (which could be a range or a set of elements of some sort). Around the variable
is a single pipebar on each side
Syntax: (expression).each do |variable(s)|
# code...
end
i.e. (0..5).each do |i|
puts "Value of local variable is #{i}"
end
break:
The break keyword terminates the innermost loop. It can also be used to terminate a method with
an associated block if called within the block (which makes the method return nil).
next:
The next keyword jumps to the next iteration of the innermost loop. Also can be used to terminate
the execution of a block if called within the block (with "yield" or "call" returning nil).
redo:
The redo keyword restarts the iteration of the innermost loop, without checking the loop
condition. If called within a block it restarts "yield" or "call".
retry:
When retry keyword appears in the rescue clause of a "begin" expression. It restarts from the
beginning of the "begin" body. See rescue explanation below.
If retry appears in the iterator, the block, or the body of the for-loop, it restars the
invocation of the iterator call, and the argument to the iterator is re-evaluated.
i.e. for i in 0...5
retry if condition # restrarts from i == 0
rescue:
The rescue keyword I guess handles errors. The begin-rescue block is like a try-catch block.
Syntax for using rescue and retry:
begin
# code... # exception raised
rescue
# code to handle error
retry # restarts from beginning
end
************************ METHODS ************************
Method names should begin with a lowercase letter.
Use the "def" keyword to define a method.
If there are no parameters you don't include any parentheses.
You can give a parameter a default value (in case when it is called an argument is not given) by
simply assigning a value in the parameter list with the equal sign.
As with all other blocks of code in Ruby, end the method definition with the "end" keyword.
Syntax:
def methodName def methodName(param1, param2, param3=default)
# code...
end
Calling a method:
To call a method you simply write the name of the function if there are no arguments given, or
with arguments you just write the arguments separated by commas and that's it, no parantheses
are used.
Syntax: methodName arg1, arg2
Return values:
Every method in Ruby returns a value by default. The return value is the value of the last
statement in the method definition.
Or you can use the "return" keyword to return one or more values. If more than one value is
returned then separate the values with commas. If more than two (one?) values are given in the
return statement then an array containing these values will be returned. If the return statement
is not followed by any values then it returns nil.
Syntax: return return value1 return value1, value2, value3
Variable Number of Parameters:
You can put one parameter with a * in front of it to specify that parameter to be a variable
parameter, meaning it can take multiple values. Basically I guess it just makes an array in the
parameter list that takes all the arguments.
Syntax: def methodname(*param)
# code...
end
Class Methods:
When a method is defined outside of the class definition, the method is marked as private by
default, whereas the methods defined in a class are public by default. The default visibility
and the private mark of the methods can be changed by "public" or "private" of the Module.??
Normally to access a class method you must instantiate an object of that class first and then
call the method on the object, but Ruby give a way to access a method without instantiating
a class. You do this by simply calling the method on the class name itself, instead of an
object.
To define a class method:
class MyClass
def someMeth
end
end
To call a method:
i.e. objName.someMeth or MyClass.someMeth
Aliases:
You can give an alias to methods or global variables. Aliases cannot be defined within the
method body. The alias of the method keeps the current definition of the method, even when
methods are overridden.
Making aliases for numbered global variables ($1, $2, etc) is prohibited because they are
built-in global variables. Overriding the built-in global variables may cause serious problems.
Syntax: alias theAliasName methodName
alias $theAliasName $globalVarName
Undef:
The "undef" keyword cancels the method definition. An "undef" cannot appear in the method body.
By using undef and alias, the interface of the class can be modified independently from the
superclass, but I think maybe it can break a program by the internal method call to "self".
Syntax: undef methodName
Using &,* Prefixes for Parameters and Arguments:
If both * and & are used in a parameter list, the & should come at the end, in fact, the ¶m
should always be the last parameter in the list.
&:
Put an & in front of the parameter name that expects a block in the parameter list in the
definition of the method.
i.e. def myMeth(blah, &theblock) ... end
When & is put before an argument name when calling a method it is used give a Proc object
as an actual block defined in the argument list.
i.e. def myMeth(&Proc.new{ block code })
*:
Put an * in front of a parameter name in order to combine all of the remaining arguments
into a single list.
i.e. def myMeth(*a) ... end
myMeth(1,2,3) # 1,2,3 all go into the 'a' Array
When * is put before an argument when calling a method it is used to expand an array in the
argument list so that each element of the array goes into a different parameter.
i.e. def myMeth(a,b,c,d) ... end
myMeth(1, *[5,6,7]) # parameters will be: a=1, b=5, c=6, d=7
************************ BLOCKS ************************
A block consists of chunks of code.
You assign a name to a block.
The code in a block is always enclosed with curly braces { }
A block is always invoked from a method with the same name as the block.
You involve a block by using the yield statement.
A block can have parameters, and so a yield statement can take arguments.
You can also pass a block as an argument to a method.
Syntax:
blockName { |param1, param2|
# code...
}
Yield:
Yield can have zero or more parameters.
Syntax: yield arg1, arg2...
i.e.
def test
puts "You are in the method"
yield
puts "You are again back to the method"
yield
end
test {
puts "You are in the block"
}
Parameters are syntactically similar to thos used in and each-do statement, in that you put them
between pipe bars: |params|
Multiple parameters will be comma separated, but between the same pair of pipe bars.
i.e.
def test
yield 5
puts "You are in the method"
yield 100
end
test { |i|
puts "You are in the block #{i}"
}
Passing blocks to methods:
By putting an "&" sign at the beginning of the last parameter in a method (note that it must be
the last parameter in the parameter list) you can designate that parameter to take a block.
If both a * and an & are used in the argument list the & should come later.
To call a block from the parameter list use: blockname.call
Syntax:
def test(&block)
block.call
end
test {
# code...
}
BEGIN and END blocks:
Every Ruby source code file can declare blocks of codeto be run as the file is being loaded and
after the program has finished executing. The BEGIN block runs as the file is being loaded, the
END block runs after the program has finished executing.
A program can contain multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered, while END blocks are executed in reverse order.
************************ MODULES AND MIXINS ************************
Modules are a way of grouping together methods, classes, and constants.
Modules give two major benefits:
- modules provide a namespace and prevent name clashes
- modules implement the mixin facility
Syntax:
module Identifier
# code...
end
Module constants are named just like class constants, with an initial uppercase letter.
Module methods are defined just like class methods. Module methods are defined with the module name
and then the dot operator and the method name.
i.e.
module ModuleName
PI = 3.14
def ModuleName.methodName
# code...
end
def ModuleName.method2
# code...
end
end
Require:
The require statement is similar to the include statement in C/C++ and the import statement in
Java. If a third program wants to use any defined module, it can simply load the module files
using the require statement.
Syntax: require "filename" # note you don't need to give the .rb extension
To make Ruby aware that included files must be searched in the current directory, use the
code: $LOAD_PATH << '.'
Or instead of using the $LOAD_PATH variable you can use "require_relative" to include files from
a relative directory.
Include:
With the include statement you can embed a module in a class.
Syntax: include modulename
If a module is defined in a separate file then you must use the require statement to get at the
file it is in, before using the include statement to identify the specific module in that file
to embed in a class.
You can define new variables and methods to act locally on the module in your class.
When accessing variables or constants from a module in your embedded module in the class, make
sure to use the :: operator to get access to them.
i.e.
$LOAD_PATH << '.'
require "filename"
class MyClass
include modulename
# can make new variables and methods to use with the module here
end
# code...
end
Or to just simply include the module without adding any extra stuff to it in the class just
use: include modulename
To call a method or variable from an embedded module in a class just use the normal way to use
a property of a class:
objName.property
Mixins:
When a class can inherit from more than one parent, the class has multiple inheritance.
Ruby does not support multiple inheritance directly, but Ruby Modules can basically take the
place of multiple inheritance using a facility called a mixin.
Mixins give a controlled way of adding functionality to classes and by providing the equivalent
of multiple inheritance they give the programmer a lot of power.
Note that mixin isn't a keyword or anything you put in the code, it is just what using modules
to give classes multiple inheritance is called. So you don't do anything extra to use mixins,
you just embed more than one module in a class, and that is a mixin.
************************ STRINGS ************************
You can use either single quotes or double quotes, but they have different meanings.
Expression Substitution:
A means of embedding the value of any Ruby expression into a string using #{ }. This is how you
include variables in a string, you don't need to split of the string with +'s or .'s.
Although when using a variable with a method in a string you must add it to the output string
with a + sign instead of putting it right in the string, as in most languages.
When printing out a variable all by itself you can just put the variable name or put it in
between quotes using the #{ } .
It looks like in a class you can refer to instance variables without the curly braces and
instead just do this: #@varname
General Delimited Strings:
You can create strings inside a pair of matching but arbitrary delimiter characters, like !, (, {, <, etc. as long as the first delimiter character is preceded by a %.
Q, q, and x have special meanings, but I think maybe any other character can be used as the
delimiter.
i.e.
%$I like Ruby$
%{I like Ruby}
%^I like Ruby^
%:I like Ruby:
%5I like Ruby5 # I assume anything will work excapt Q, q, x
By default I think a double-quoted string is made.
Q creates a double-quoted string.
q creates a single-quoted string.
x I think creates a command out of the string.
i.e.
%Q{I like Ruby} # "I like Ruby"
%q{I like Ruby} # a single quoted string
%x!ls! # equivalent to back tick command output 'ls'
Ruby I think has the standard escape characters.
The default encoding set for Ruby is ASCII. To change the encoding set put $KCODE at the beginning
of the program. The codes to set $KCODE equal to are:
a - ASCII (default)
e - EUC
n - none (same as ASCII)
u - UTF-8
i.e. $KCODE = 'u'
To create a new string object, rather than a setting a string literal to a variable, do:
myStr = String.new("thestring")
There are a ton of built-in String methods. See them all here:
http://www.tutorialspoint.com/ruby/ruby_strings.htm
Some methods:
gsub(regex,replacement) - global substitution. first param is substring to find, second
param is the replacement substring
The unpack(format) String method decodes a string according to the given format, return an array
of each value extracted. The format string consists of a sequence of single-character directives.
To see all the directives check out the webpage mentioned directly above.