Today I Learned (2021)

January 15

🙊 TIL about Monkey Patching

Monkey patching “refers to the practice of extending or modifying existing code by changing classes at run-time” (Monkey Patching is Destroying Ruby).

That’s how I also learned that Rails methods like .blank? are actually monkey patches. And also that it’s easy to write your own. All you have to do is open a native class and add your own method (which you can now call on every string instance):

class String
def monkey
🐒
end
end

Source: Learn Enough Ruby To Be Dangerous


January 14

♠️ TIL about Ruby’s array method called product

The product method “returns an array of all combinations of elements of arrays” like so:

RANKS = (7..10).to_a + [:jack, :queen, :king, :ace]

SUITS = [:hearts, :clubs, :diamonds, :spades]

SUITS.product(RANKS)=> [[:hearts, 7], [:hearts, 8], [:hearts, 9], [:hearts, 10], [:hearts, :jack], [:hearts, :queen], [:hearts, :king], [:hearts, :ace], [:clubs, 7], [:clubs, 8], [:clubs, 9], [:clubs, 10], [:clubs, :jack], [:clubs, :queen], [:clubs, :king], [:clubs, :ace], [:diamonds, 7], [:diamonds, 8], [:diamonds, 9], [:diamonds, 10], [:diamonds, :jack], [:diamonds, :queen], [:diamonds, :king], [:diamonds, :ace], [:spades, 7], [:spades, 8], [:spades, 9], [:spades, 10], [:spades, :jack], [:spades, :queen], [:spades, :king], [:spades, :ace]]

Docs: product

Source: Testing Ruby Applications with RSpec