mirror of
https://github.com/jbranchaud/til
synced 2026-01-19 23:18:01 +00:00
Compare commits
4 Commits
6984685276
...
0f06e42884
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f06e42884 | ||
|
|
b492a9d765 | ||
|
|
543a82730d | ||
|
|
460473a87f |
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1508 TILs and counting..._
|
||||
_1510 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -888,6 +888,7 @@ _1508 TILs and counting..._
|
||||
- [Access Instance Variables](python/access-instance-variables.md)
|
||||
- [Create A Dummy DataFrame In Pandas](python/create-a-dummy-dataframe-in-pandas.md)
|
||||
- [Dunder Methods](python/dunder-methods.md)
|
||||
- [Override The Boolean Context Of A Class](python/override-the-boolean-context-of-a-class.md)
|
||||
- [Store And Access Immutable Data In A Tuple](python/store-and-access-immutable-data-in-a-tuple.md)
|
||||
- [Test A Function With Pytest](python/test-a-function-with-pytest.md)
|
||||
- [Use pipx To Install End User Apps](python/use-pipx-to-install-end-user-apps.md)
|
||||
@@ -1221,6 +1222,7 @@ _1508 TILs and counting..._
|
||||
- [Find The Min And Max With A Single Call](ruby/find-the-min-and-max-with-a-single-call.md)
|
||||
- [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md)
|
||||
- [Format A Hash Into A String Template](ruby/format-a-hash-into-a-string-template.md)
|
||||
- [Forward All Arguments To Another Method](ruby/forward-all-arguments-to-another-method.md)
|
||||
- [Generate A Signed JWT Token](ruby/generate-a-signed-jwt-token.md)
|
||||
- [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md)
|
||||
- [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md)
|
||||
|
||||
@@ -15,10 +15,8 @@ const remove = (items,index) => {
|
||||
};
|
||||
|
||||
const list = [1,2,3,4,5];
|
||||
remove(list, 2);
|
||||
// [1,2,3,4]
|
||||
list
|
||||
// [1,2,3,4,5]
|
||||
remove(list, 2); // [1,2,4,5]
|
||||
// list still [1,2,3,4,5]
|
||||
```
|
||||
|
||||
It only took a couple lines of code and immutability is baked in.
|
||||
|
||||
86
python/override-the-boolean-context-of-a-class.md
Normal file
86
python/override-the-boolean-context-of-a-class.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# Override The Boolean Context Of A Class
|
||||
|
||||
Everything in Python has a truthiness that can be checked with `bool()`. An
|
||||
empty list (`[]`) is falsy. A non-empty list (`[1,2,3]`) is truthy. Similar
|
||||
with numbers:
|
||||
|
||||
```python
|
||||
>>> bool(0)
|
||||
False
|
||||
>>> bool(1)
|
||||
True
|
||||
```
|
||||
|
||||
Any instance of an object is going to be truthy by default. If you want to
|
||||
control in what context an instance is considered truthy or falsy, you can
|
||||
override
|
||||
[`__bool__()`](https://docs.python.org/3/reference/datamodel.html#object.__bool__).
|
||||
If that's not implemented, but
|
||||
[`__len__()`](https://docs.python.org/3/reference/datamodel.html#object.__len__)
|
||||
is, then it will fallback to that.
|
||||
|
||||
Let's look at a few example classes:
|
||||
|
||||
```python
|
||||
class CartZero:
|
||||
def __init__(self, items=[]):
|
||||
self.items = items or []
|
||||
|
||||
class CartBool:
|
||||
def __init__(self, items=[]):
|
||||
self.items = items or []
|
||||
|
||||
def __bool__(self):
|
||||
print("__bool__() override")
|
||||
return bool(self.items)
|
||||
|
||||
class CartLen:
|
||||
def __init__(self, items=[]):
|
||||
self.items = items or []
|
||||
|
||||
def __len__(self):
|
||||
print("__len__() override")
|
||||
return len(self.items)
|
||||
|
||||
class CartBoolAndLen:
|
||||
def __init__(self, items=[]):
|
||||
self.items = items or []
|
||||
|
||||
def __len__(self):
|
||||
print("__len__() override")
|
||||
return len(self.items)
|
||||
|
||||
def __bool__(self):
|
||||
print("__bool__() override")
|
||||
return bool(self.items)
|
||||
|
||||
cart1 = CartZero()
|
||||
cart2 = CartBool()
|
||||
cart3 = CartLen()
|
||||
cart4 = CartBoolAndLen()
|
||||
|
||||
print("CartZero() -> %s" %(bool(cart1)))
|
||||
print('')
|
||||
print("CartBool() -> %s" %(bool(cart2)))
|
||||
print('')
|
||||
print("CartLen() -> %s" %(bool(cart3)))
|
||||
print('')
|
||||
print("CartBoolAndLen() -> %s" %(bool(cart4)))
|
||||
```
|
||||
|
||||
An 'empty' `Cart` be default is truthy. However, we can override some
|
||||
combination of `__bool__()` or `__len__()` to give it a boolean context that
|
||||
goes `false` when "empty".
|
||||
|
||||
```
|
||||
CartZero() -> True
|
||||
|
||||
__bool__() override
|
||||
CartBool() -> False
|
||||
|
||||
__len__() override
|
||||
CartLen() -> False
|
||||
|
||||
__bool__() override
|
||||
CartBoolAndLen() -> False
|
||||
```
|
||||
45
ruby/forward-all-arguments-to-another-method.md
Normal file
45
ruby/forward-all-arguments-to-another-method.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# Forward All Arguments To Another Method
|
||||
|
||||
There are three types of arguments that a Ruby method can receive. Positional
|
||||
arguments, keyword arguments, and a block argument.
|
||||
|
||||
A method that deals with all three might be defined like this:
|
||||
|
||||
```ruby
|
||||
def forwarding_method(*args, **kwargs, &block)
|
||||
# implementation
|
||||
end
|
||||
```
|
||||
|
||||
Now lets say we have some concrete method that we want to forward these
|
||||
arguments to:
|
||||
|
||||
```ruby
|
||||
def concrete_method(*args, **kwargs)
|
||||
x = args.first || 1
|
||||
key, y = kwargs.first || [:a, 2]
|
||||
|
||||
puts "Dealing with #{x} and key #{key}: #{y}"
|
||||
|
||||
yield(x, y)
|
||||
end
|
||||
```
|
||||
|
||||
We could forward arguments the longhand way like this:
|
||||
|
||||
```ruby
|
||||
def forwarding_method(*args, **kwargs, &block)
|
||||
concrete_method(*args, **kwargs, &block)
|
||||
end
|
||||
```
|
||||
|
||||
However, since Ruby 2.7 we have access to a shorthand "triple-dot" syntax for
|
||||
forwarding all arguments.
|
||||
|
||||
```ruby
|
||||
def forwarding_method(...)
|
||||
concrete_method(...)
|
||||
end
|
||||
```
|
||||
|
||||
[source](https://ruby-doc.org/3.3.6/syntax/methods_rdoc.html#label-Argument+Forwarding)
|
||||
Reference in New Issue
Block a user