[en] How to prevent direct access to internal components and make contracts clearer and more explicit. 🤯
[pt-BR] Como prevenir acesso direto a componentes internos e tornar contratos mais claro e explícitos. 🤯
[en] How to prevent direct access to internal components and make contracts clearer and more explicit. 🤯
[pt-BR] Como prevenir acesso direto a componentes internos e tornar contratos mais claro e explícitos. 🤯
A princípio, pode parecer estranho que um objeto não possa ser alterado após a sua criação, mas isso é algo que acontece com alguns tipos de objetos no Ruby, como por exemplo, Symbol e Integer.
Nesse post, abordo o conceito de imutabilidade no Ruby, discutindo como criar objetos imutáveis e explorando os benefícios dessa abordagem.
Você pode ver mais aqui 👇🏻
https://aristotelescoutinho.com.br/entendendo-objetos-imutaveis-no-ruby/
I've been copying a variation of this snippet into most Ruby projects:
class BigDecimal
def inspect
"BigDecimal(\"#{to_s(?F)}\")"
end
end
It overrides the default appearance of a BigDecimal in an irb/pry/rails console. Why?
1. Easier to visually scan than exponential notation
2. Can be copy-pasted to get another bigdecimal (otherwise using exp notation yields a Float instance)
If you wish to memoize (cache / calculate only once) a value, a Hash with a block in ruby is a good way to do it.
For example:
h = Hash.new do |hash, key|
hash[key] = "Default value for #{key} "
end
h.fetch(:no_such, "not defined")
#=> "not defined"
h[:no_such]
# => "Default value for no_such"
This is means the value for h[:no_such] gets set the first time it is accessed and no longer needs to be calculated with the block, but fetch does not use that default proc.
When you use the block syntax with Hash.new to define a default value, you lock yourself to only using the square bracket syntax for value lookup. The fetch method ignores the block, default, and default_proc.
This bit me hard this week, and my pair, @gd, got to watch me flounder on why fetch wasn’t getting the default value.
By the way, the Hash.new with a block is great for memoization of calculated or network lookup data.
OK experienced rubyists - putting your hindsight glasses on name 1 ruby topic or facet of ruby you wished you had studied more when you were getting started out with ruby.