-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruby_stuff.txt
More file actions
1815 lines (1185 loc) · 39.1 KB
/
ruby_stuff.txt
File metadata and controls
1815 lines (1185 loc) · 39.1 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 Installation:
==================
- RVM .. check the new virtual enviroment for ruby
1.3 Ruby Versions
Rails generally stays close to the latest released Ruby version when it's released:
Rails 6 requires Ruby 2.5.0 or newer.
Rails 5 requires Ruby 2.2.2 or newer.
Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer.
Rails 3.2.x is the last branch to support Ruby 1.8.7.
Rails 3 and above require Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially. You should upgrade as early as possible.
-------
--> https://rvm.io/workflow/projects
echo "2.7.2" > .ruby-version
echo "forem" > .ruby-gemset
operators
========================================================================
+ Addition − Adds values on either side of the operator. a + b will give 30
− Subtraction − Subtracts right hand operand from left hand operand. a - b will give -10
* Multiplication − Multiplies values on either side of the operator. a * b will give 200
/ Division − Divides left hand operand by right hand operand. b / a will give 2
% Modulus − Divides left hand operand by right hand operand and returns remainder. b % a will give 0
** Exponent − Performs exponential (power) calculation on operators.
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.
<=> Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second. (a <=> b) returns -1.
=== Used to test equality within a when clause of a case statement. (1...10) === 5 returns true.
.eql? True if the receiver and argument have both the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) is false.
equal? True if the receiver and argument have the same object id. if aObj is duplicate of bObj then aObj == bObj is true, a.equal?bObj is false but a.equal?aObj is true.
= Simple assignment operator, assigns values from right side operands to left side operand. c = a + b will assign the value of a + b into c
+= Add AND assignment operator, adds right operand to the left operand and assign the result to left operand. c += a is equivalent to c = c + a
-= Subtract AND assignment operator, subtracts right operand from the left operand and assign the result to left operand. c -= a is equivalent to c = c - a
*= Multiply AND assignment operator, multiplies right operand with the left operand and assign the result to left operand. c *= a is equivalent to c = c * a
/= Divide AND assignment operator, divides left operand with the right operand and assign the result to left operand. c /= a is equivalent to c = c / a
%= Modulus AND assignment operator, takes modulus using two operands and assign the result to left operand. c %= a is equivalent to c = c % a
**= Exponent AND assignment operator, performs exponential (power) calculation on operators and assign value to the left operand. c **= a is equivalent to c = c ** a
& Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12, which is 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (a | b) will give 61, which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49, which is 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~a ) will give -61, which is 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240, which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15, which is 0000 1111
and Called Logical AND operator. If both the operands are true, then the condition becomes true. (a and b) is true.
or Called Logical OR Operator. If any of the two operands are non zero, then the condition becomes true. (a or b) is true.
&& Called Logical AND operator. If both the operands are non zero, then the condition becomes true. (a && b) is true.
|| Called Logical OR Operator. If any of the two operands are non zero, then the condition becomes true. (a || b) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(a && b) is false.
not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. not(a && b) is false.
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y
.. Creates a range from start point to end point inclusive. 1..10 Creates a range from 1 to 10 inclusive.
... Creates a range from start point to end point exclusive. 1...10 Creates a range from 1 to 9.
defined? variable # True if variable is initialized
foo = 42
defined? foo # => "local-variable"
defined? $_ # => "global-variable"
defined? bar # => nil (undefined)
defined? method_call # True if a method is defined
defined? puts # => "method"
defined? puts(bar) # => nil (bar is not defined here)
defined? unpack # => nil (not defined here)
# True if a method exists that can be called with super user
defined? super
defined? super # => "super" (if it can be called)
defined? super # => nil (if it cannot be)
defined? yield # True if a code block has been passed
defined? yield # => "yield" (if there is a block passed)
defined? yield # => nil (if there is no block)
MR_COUNT = 0 # constant defined on main Object class
module Foo
MR_COUNT = 0
::MR_COUNT = 1 # set global count to 1
MR_COUNT = 2 # set local count to 2
end
puts MR_COUNT # this is the global constant
puts Foo::MR_COUNT # this is the local "Foo" constant
String
========================================================================
"ruby".size # 4
"".size == 0 # true
"".empty? # true
string = "abc123" string[0,3] # "abc"
string[3,3] # "123"
string = "abc123" string[0..-2] # "abc12"
string[0..2] = "" p string # "123"
string = "Today is Saturday" string.include?("Saturday") # true
string = "Today is Sunday" string.index("day") # 2
binary_string = "1101" binary_string.rjust(8, "0") # "00001101"
binary_string = "1111" binary_string.ljust(8, "0") # "11110000"
lang1 = "ruby" lang2 = "Ruby" lang1.upcase == lang2.upcase
extra_space = " test " extra_space.strip # "test"
string = "ruby programming" string.start_with? "ruby" # true
string = "ruby programming" string.end_with? "programming" # true
string = "bacon is expensive" string.delete_suffix(" is expensive") # "bacon"
string = "a b c d" string.split # ["a", "b", "c", "d"]
csv = "a,b,c,d" string.split(",") # ["a", "b", "c", "d"]
arr = ['a', 'b', 'c'] arr.join # "abc"
arr = ['a', 'b', 'c'] arr.join("-") # "a-b-c"
"49".to_i
"123".match?(/\A-?\d+\Z/) # true
"123bb".match?(/\A-?\d+\Z/) # false
string = ""
string << "hello"
string << " "
string << "there" # "hello there"
"rubyguides".each_char { |ch| puts ch }
array_of_characters = "rubyguides".chars # ["r", "u", "b", "y", "g", "u", "i", "d", "e", "s"]
"abcd".upcase # "ABCD"
"ABCD".downcase # "abcd"
b = <<-STRING
aaa
bbb
ccc
STRING
a = %Q(aaa
bbb
ccc
)
string = "We have many dogs" string.gsub("dogs", "cats") # "We have many cats"
string = "abccc" string.gsub("c", "") # "ab"
string = "We have 3 cats" string.gsub(/\d+/, "5") # "We have 5 cats"
title = "the lord of the rings" title.gsub(/\w+/) { |word| word.capitalize } # "The Lord Of The Rings"
puts "What's your name?"
name = gets
# type something...
name = gets.chomp <-- remove "\n"
"abcd?".chomp("?") # "abcd"
"abc".encoding # Encoding:UTF-8
"abc".force_encoding("UTF-8")
str = "aaab"
str.count("a")
# 3
str.count("b")
# 1
Time
========================================================================
Time.now.to_i Time in milli seconds
Time.now.to_i / 1000 = seconds
Hashes & Arrays
========================================================================
Arrays
------
array = [1, 2, 3]
array.each { |item| print “-#{item}-” }
-1–2–3-
array.select { |item| item > 2 }
[3]
array.map { |item| item * 2 }
[2, 4, 6]
array.delete_if { |item| item == 1 }
[2, 3]
array.reject { |item| item % 3 == 0 }
[1, 2]
array.count
array.count { |item| item % 3 == 0 }
numbers = [1, 2, 3, 4, 5]
#An array of Integers
words = ["See", "Spot", "run"]
#An array of Strings
mixed = ["hello", 5, true, 3.0]
#An array with a String, Integer, Boolean, and Float
empty = []
#An empty array4
Creating An Array Of Symbols
symbols = %i(a b c)
[:a, :b, :c]
Similar to the string version %w:
strings = %w(a b c) # also %w[a b c]
["a", "b", "c"]
More array methods
[1,2,3].all? {|i| i>2} # false
[1,2,3].all? {|i| i<4} # true
[1,2,3].any? {|i| i>2} # true
Hashes
========================================================================
hash = { ‘name’ => ‘Vadim’, ‘location’ => ‘Moon’ }
hash.each do |key, value|
puts “key: #{key}, value: #{value}”
end
hash.each_key{ |key| puts “key: #{key}” }
hash.each_value { |val| puts “val: #{val}” }
hash.select { |key, val| key == “name” }
hash.keep_if{ |key, val| key == “name” }
hash.reject { |key, val| key == “name” }
profile = {
"name" => "Magnus",
"profession" => "chess player"
"ranking" => 1,
"grandmaster?" => true
}
# "name", "profession", "ranking", and "grandmaster?" are the keys. "Magnus", "chess player", 1 and true are the values.
puts profile["name"] # => Magnus
- Ruby Hash New
#Creating a hash through literal notation:
lunch = {
"protein" => "chicken",
"greens" => "lettuce",
"organic?" => true
}
#Creating a hash through Hash.new
lunch = Hash.new
puts lunch # => {}
- Ruby Hash Bracket Notation Adding Pairs
#Bracket notation applies to any hash, regardless of how it was initialized
teammates = Hash.new
teammates["forward"] = "Messi"
salary = {
"starting" => 40000
}
salary["mid-level"] = 60000
- Ruby Multidimensional Arrays
ulti_array = [[0,1,2,3],[4.5, true, "hi"]]
# Accessing the array at index 1
puts multi_array[1] # => [4.5, true, "hi"]
# Accessing the element at index 0 within the array at index 1
puts multi_array[1][0] # => 4.5
- Ruby Array Index
example = ["Car", "Boar", 45, 9.9, true]
#For an array named `example`, you can retrieve an item of a particular index by referencing its index.
puts example[2] # => 45
puts example[0] # => Car
- Ruby Combined Comparison Operator
puts "Keanu" <=> "Adrianna" # The first letters of each word are compared in ASCII order and since "K" comes after "A", 1 is printed.
puts 1 <=> 2 # -1
puts 3 <=> 3 # 0
#<=> can also be used inside of a block and to sort values in descending order:
my_array = [3, 0, 8, 7, 1, 6, 5, 9, 4]
my_array.sort! { |first_num, second_num| second_num <=> first_num }
print my_array
#Output => [9, 8, 7, 6, 5, 4, 3, 1, 0]
- Ruby Method Splat
#The * preceding the parameter "clubs" allows for multiple arguments to be passed into the method when you actually call it.
def extra_curriculars(*clubs)
clubs.each { |club| puts "After school, I'm involved with #{club}" }
end
extra_curriculars("chess club", "gymnastics", "anime club", "library services")
#Output
#After school, I'm involved with chess club
#After school, I'm involved with gymnastics
#After school, I'm involved with anime club
#After school, I'm involved with library services
- Ruby Block Parameter & each
# The block, {|i| puts i}, is passed the current array item each time it is evaluated. This block prints the item.
[1, 2, 3, 4, 5].each { |i| puts i }
- Ruby .collect Method
first_arr = [3, 4, 5]
second_arr = first_arr.collect { |num| num * 5 }
print second_arr #Output => [15, 20, 25]
# In this example, the .collect method is used to multiply each number within first_arr by 5.
# The outcome is then saved inside of the second_arr variable and printed to the console.
# The original first_arr is left unchanged.
- concat
# declaring array
a = ["abc", "xyz", "dog"]
# declaring array
b = ["cow", "cat", "dog"]
# COMBINING TWO ARRAYS
puts "combining a and b : #{a.concat(b)}\n\n"
- join
# declaring array
a = [18, 22, 33, nil, 5, 6]
# join
puts "join : #{a.join(",")}\n\n"
--> 18,22,33,,5,6
also
a * ","
a * 2 --> repeat the array twice + concat
- select, map & reduce
def sum(n)
# start with total = 0
(0..n).reduce(0) {|total, n| total + n ** 2}
end
puts sum(3) # --> 14
.reduce(0){|sum, indv| sum + indv} #is the same as .reduce(:+)
people = [
{
job_title: "car enthusiast",
salary: "14000"
},
{
job_title: "developer",
salary: "12000"
}
]
# sum all salaries of people with job title developer
puts people.select{|x| x[:job_title] == "developer"}.map{|y| y[:salary].to_i}.reduce(:+)
- map &
arr = "1,3,4"
puts arr.split(",").map(&:to_i).inspect
# [1, 3, 4]
OpenStruct
========================================================================
- Similar to hash
require "ostruct"
person = OpenStruct.new
person.name = "John Smith"
person.age = 70
person.name # => "John Smith"
person.age # => 70
person.address # => nil
.. also
puts person.send("name")
puts person.send(:name)
australia = OpenStruct.new(:country => "Australia", :capital => "Canberra")
puts australia.send "country"
- If two openstructs have the same keys & values .. == -> true
- delete
person = OpenStruct.new(name: "John", age: 70, pension: 300)
person.delete_field("age") # => 70
person # => #<OpenStruct name="John", pension=300>
- to_h & to_json
puts australia.to_h # print as hash
puts australia.marshal_dump # this also
{:country=>"Australia", :capital=>"Canberra"}
to convert to json string
h = { foo: { bar: 1 } } # {:foo=>{:bar=>1}}
puts h.to_json # {"foo":{"bar":1}}
obj1 = OpenStruct.new(h)
#<OpenStruct foo={:bar=>1}>
puts obj1.to_h.to_json
{"foo":{"bar":1}}
- nested openstructus
obj2 = JSON.parse(h.to_json, object_class: OpenStruct)
#<OpenStruct foo=#<OpenStruct bar=1>>
Controls & Loops
========================================================================
- loops
- if / switches
tv_show = "Bob's Burgers"
case tv_show
when "Archer"
puts "I don't like the voice of Archer."
when "Bob's Burgers"
puts "I love the voice of Bob Belcher."
else
puts "I don't know who voices this cartoon."
end
- respond_to?
puts "A".respond_to?(:push)
# => false
# Here, the following Ruby code will return false since .push can’t be called on a String object.
puts "A".respond_to?(:next)
# => true
# Here, however, the following Ruby code will return true since .next can be called on a String object. Calling .next on the letter “A” would return the letter “”.
- Ruby Conditional Assignment Operator
boyfriend = nil
boyfriend ||= "Jimmy Jr."
boyfriend ||= "Josh"
puts boyfriend
# => "Jimmy Jr."
# In this example, since the original value of boyfriend is set to nil which is nothing, Ruby assigns it a value of "Jimmy Jr." on the following line. Once boyfriend holds this real value, another reassignment is overlooked by Ruby and the previous value holds.
- Ruby .push Method Alternative (arrays, string)
array = [1, 2, 3]
array << 4
print array
#Output => [1, 2, 3, 4]
puts "Hello," << " welcome to Codecademy."
#Output => Hello, welcome to Codecademy.
array.pop --> [1,2] return 3
array.push(3) --> [1,2,3]
Or
array.unshift(3) --> [3,1,2]
- Ruby “next” Keyword
for i in 1..10
next if i % 2 == 0
puts i
end
#In this example, the next keyword along with a shorthand if statement is used to skip over the even numbers in the sequence.
- times
5.times { puts ""Codecademy"" }
- Ruby while Loop
a = 0
while a < 5 do
# do something
a += 1
end
- Ruby Range
(-1..-5).to_a #=> []
(-5..-1).to_a #=> [-5, -4, -3, -2, -1]
('a'..'e').to_a #=> ["a", "b", "c", "d", "e"]
('a'...'e').to_a #=> ["a", "b", "c", "d"]
- Ruby loop
- Ruby until Loop
- Ruby for Loop
x = 4
# using while loop
# here condtional is x i.e. 4
while x >= 1
# statements to be executed
puts "GeeksforGeeks"
x = x - 1
# while loop ends here
end
- break
loop do
puts "GeeksforGeeks"
val = '7'
# using boolean expressions
if val == '7'
break
end
# ending of ruby do..while loop
end
- next
for x in 0..6
# Used condition
if x+1 < 4 then
# Using next statement
next
end
# Printing values
puts "Value of x is : #{x}"
end
- until
var = 7
# using until loop
# here do is optional
until var == 11 do
# code to be executed
puts var * 10
var = var + 1
# here loop ends
end
Classes & Variables
========================================================================
- Ruby Class Variables
class Child
@@children = 0 <---- calss variable
def initialize(name, birth_year)
@name = name <---- object variable
@birth_year = birth_year
@@children +=1
end
def self.children_added <---- class method
return @@children
end
end
naomi = Child.new("Naomi", 2006)
bertha = Child.new("Bertha", 2008)
puts Child.children_added # => 2
- Ruby .new Method
class Fighter
def initialize(name, style, division, age)
@name = name
@style = style
@division = division
@age = age
end
end
conor = Fighter.new("Conor", "mixed martial arts", "Welterweight", 31)
- Ruby Instance Variable
class Student
def initialize(name, grade)
@name = name
@grade = grade
end
end
# In this example, name and grade are the instance variables.
- Ruby super Keyword
class Trip
def initialize(duration, price)
@duration = duration
@price = price
end
end
class Cruise < Trip
def initialize(duration, price)
super
end
end
spain_backpacking = Trip.new(14, 800.00)
carnival = Cruise.new(7, 2400.00)
#In this example, the Cruise class inherits from the Trip class and all of its attributes, including duration and price, are carried over with the super keyword.
- Ruby attr_reader attr_writer Methods
class Student
attr_reader :name
attr_writer :name
def initialize(name)
@name = name
end
end
#In this example, Ruby is able to both read and write the @name instance variable since it was passed to attr_reader and attr_writer as a symbol.
top_student = Student.new("Jyothi")
puts top_student.name # => Jyothi
#In classes with attr_reader, instance variables can be accessed using . notation
puts top_student.name # => Jyothi
top_student.name = "Anika"
puts top_student.name # => Anika
#In classes with attr_writer, instance variables can be reassigned using . notation
- Ruby attr_accessor Method
class CollegeStudent
attr_reader :dorm
attr_accessor :major
def initialize(dorm, major)
@dorm = dorm
@major major
end
end
attr_reader : This accessor generates the automatic Getter method for the given item.
attr_writer : This accessor generates the automatic Setter method for the given item.
attr_accessor : This accessor generates the automatic Getter & Setter method for the given item.
So you can use:
puts object.dorm # only
puts object.major # both, getter and setter
object.major = 444
- send
receiver name payload
| | |
__________ ______ ______
"a-string".send(:split, '-', 3)
as
receiver name payload
| | |
__________ _____ ______
"a-string".split('-', 3)
Modules
======================================================================================
- Define
#A Ruby module can be created using the module keyword followed by the module name written in CapitalizedCamelCase format finalized with an end.
module MyPizza
FAVE_TOPPING = "Buffalo Chicken"
end
#In this example, myPizza is a module that holds a constant, FAVE_TOPPING, set equal to the string, Buffalo Chicken.
- Ruby namespace
#To retrieve a constant from the Math module, the scope resolution operator (::), should be used.
puts Math::PI
# => 3.141592653589793
#In this example, Ruby is targetting the PI constant from the Math module using the scope resolution operator, (::), and printing its value to the console.
- include
module Cream
def cream?
true
end
end
class Cookie
include Cream
end
cookie = Cookie.new
p cookie.cream?
- private & protected
module Encryption
private
def encrypt(string)
Digest::SHA2.hexdigest(string)
end
end
Private methods
In Ruby, a private method (or private message handler) can only respond to a message with an implicit receiver (self).
Protected methods
In Ruby, a protected method (or protected message handler) can only respond to a message with an implicit/explicit receiver (object) of the same family. It also cannot respond to a message sent from outside of the protected message handler context.
* Indeed, when a message is sent by using this method, the private and protected policies are bypassed
- Ruby 2.7+ allows private methods to be called with self as receiver
puts "hello world!" # => hello world!
self.puts "hello world!" # => hello world!
Object.new.puts "hello world!" # NoMethodError
(Mixins) include & extend
======================================================================================
* In simple words, the difference between include and extend is that:
- ‘include’ is for adding methods only to an instance of a class
- ‘extend’ is for adding methods to the class but not to its instance.
# Creating a module contains a method
module Geek
def prints(x)
puts x
end
end
class GFG
# by using both include and extend
# we can access them by both instances
# and class name.
include Geek
extend Geek
end
# access the prints() in Geek
# module by include in Lord class
GFG.new.prints("Howdy") # object access
# access the prints() in Geek
# module by extend it in Lord class
GFG.prints("GeeksforGeeks!!") # class access
- Ruby Mixins
# module consist 2 methods
module G
def g1
end
def g2
end
end
# module consist 2 methods
module GFG
def gfg1
end
def gfg2
end
end
# Creating a class
class GeeksforGeeks
include G
include GFG
def s1
end
end
# Creating object
gfg = GeeksforGeeks.new
# Calling methods
gfg.g1
gfg.g2
gfg.gfg1
gfg.gfg2
gfg.s1
- Polymorphism in Ruby
- Polymorphism using inheritance (class Car < Vehicle ... override same emthod)
- Polymorphism using Duck-Typing (pass class object to method --> delegate)
- Variable Number of Parameters
def geeks (*var)
# to display the total number of parameters
puts "Number of parameters is: #{var.length}"
# using for loop
for i in 0...var.length <--------
puts "Parameters are: #{var[i]}"
end
end
# calling method by passing
# variable number of arguments
geeks "GFG", "G4G"
geeks "GeeksforGeeks"
- super
def display a, b
# calling the superclass method
# by default it will pass
# both the arguments
super
# passing only one argument
super a
# passing both the argument
super a, b
# calling the superclass method
# by default it will not pass
# both the arguments
super()
end
- module can access the includer self variables
module A
def go
puts "something #{self.v}"
end
end
class B
include A
attr_accessor :v
end
b = B.new
b.v = 33
puts b.go
# something 33
# if we extend instead of include, the go method will be part of the class, not object
# and then you can't use instant variables (v) ..
B.go --> doesn't work
- letting the module once its included
module A
def class_method
puts "1 class method #{v}"
end
def self.included(base)
def class_method <------ as object method
puts "2 class method #{v}"
end
def base.class_method2 <------ as class method will override methods in ClassMethods
puts "3 class method #{v}"
end
base.extend(ClassMethods) <------ extend class methods
end
module ClassMethods
def class_method
puts "C : class method"