-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonkey_patching.rb
More file actions
29 lines (25 loc) · 1.22 KB
/
Copy pathmonkey_patching.rb
File metadata and controls
29 lines (25 loc) · 1.22 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
# Monkey Patching
# Monkey patching is a technique in programming where you can modify or extend the behavior of existing classes or modules at runtime (mostly use in string, array, and hash).
# This can be useful for adding new functionality, fixing bugs, or changing the behavior of existing methods without modifying the original source code.
class String
# Adding a new method to count the number of vowels in a string
# self.count is a built-in method that counts the occurrences of specified characters in the string.
# self refers to the instance of the String class on which the method is called.
def count_vowels
self.count('aeiouAEIOU')
end
end
p "Hello World".count_vowels # Output: 3
test = "Monkey Patching"
p test.count_vowels # Output: 4
class Array
# Adding a new method to check if the array is sorted?
# self.sort is a built-in method that returns a new array with the elements sorted in ascending order.
# self refers to the instance of the Array class on which the method is called.
# And self.sort is a sorted method that returns a new array with the elements sorted in ascending order.
def sorted?
self == self.sort
end
end
p [1, 2, 3].sorted? # Output: true
p [3, 2, 1].sorted? # Output: false