Created
March 20, 2023 07:06
-
-
Save wyodeb/74a5187b0ff6b22cfa5c91b0603b92f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example 1: Monkey patching the String class | |
class String | |
def to_b | |
return true if self == "true" | |
return false if self == "false" | |
raise ArgumentError.new("invalid value for Boolean: #{self}") | |
end | |
end | |
# Usage: | |
puts "true".to_b # outputs: true | |
puts "false".to_b # outputs: false | |
puts "foo".to_b # raises ArgumentError: invalid value for Boolean: foo | |
# Example 2: Monkey patching the Array class | |
class Array | |
def sum | |
self.inject(0) { |sum, x| sum + x } | |
end | |
end | |
# Usage: | |
puts [1, 2, 3].sum # outputs: 6 | |
puts [4, 5, 6].sum # outputs: 15 | |
# Example 3: Monkey patching the Hash class | |
class Hash | |
def keys_to_strings | |
new_hash = {} | |
self.each { |k, v| new_hash[k.to_s] = v } | |
new_hash | |
end | |
end | |
# Usage: | |
h = { name: "John", age: 30 } | |
puts h.keys_to_strings # outputs: {"name"=>"John", "age"=>30} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment