Re:Diggin’ and Fetchin’ with TruffleRuby
by pqdbr on Wednesday August 25, 2021 @04:27PM
(#28306479)
I love #fetch and I feel it makes my code safer. I use it all the time.
{ success: true }[:sucess] is nil (notice that you got a falsy value due to a typo in `success`), while { success: true }.fetch(:sucess) will raise and warn you about your mistake, and Ruby is nice enough to throw a `Did you mean? :success` for you there.
One small tip about fetch: remember that every method in Ruby always fully evaluates all its arguments.
So, if you use it like { data: [ ] }.fetch(:data, get_data_via_very_expensive_method_call), the method `get_data_via_very_expensive_method_call` will always be called, because it's an argument and it will be evaluated BEFORE it's passed to fetch.
That's why one should prefer using the block form in cases like this:
{ data: [ ] }.fetch(:data) { get_data_via_very_expensive_method_call } will only call `get_data_via_very_expensive_method_call` if the Hash doesn't have the :data key.
{ success: true }[:sucess] is nil (notice that you got a falsy value due to a typo in `success`), while { success: true }.fetch(:sucess) will raise and warn you about your mistake, and Ruby is nice enough to throw a `Did you mean? :success` for you there.
One small tip about fetch: remember that every method in Ruby always fully evaluates all its arguments.
So, if you use it like { data: [ ] }.fetch(:data, get_data_via_very_expensive_method_call), the method `get_data_via_very_expensive_method_call` will always be called, because it's an argument and it will be evaluated BEFORE it's passed to fetch.
That's why one should prefer using the block form in cases like this:
{ data: [ ] }.fetch(:data) { get_data_via_very_expensive_method_call } will only call `get_data_via_very_expensive_method_call` if the Hash doesn't have the :data key.