def track_for stat
# This is a hash with 2 elements of proc
{
symbol: -> { send(stat) },
array: -> { send(stat[0], stat[1]) }
}.freeze[stat.class.name.underscore.to_sym].call
end
freeze[stat.class.name.underscore.to_sym].call , I have no idea about this code. What is the function of the code inside []
, and why use call
method? Anyone who can help me? Much appreciate it.
Ruby Freeze method done following things on different objects, basically it's make object constant or immutable in ruby. But you can assign new string or change its reference. Once the reference change then it is not freeze (or constant) object. arr array is frozen means you can't change the array.
By using #freeze, I'm able to create a constant that's actually constant. This time, when I attempt to modify the string, I get a RuntimeError. Here' a real-world example of this in the ActionDispatch codebase. Rails hides sensitive data in logs by replacing it with the text "[FILTERED]".
Object.freeze() Method Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object. freeze() preserves the enumerability, configurability, writability and the prototype of the object.
You can always freeze your hashes in Ruby for safety if you want to. All that's missing is some sugar for declaring immutable hash literals.
Ruby Freeze method done following things on different objects, basically it's make object constant or immutable in ruby.
str = "this is string"
str.freeze
str.replace("this is new string") #=> FrozenError (can't modify frozen String)
or
str[0] #=> 't'
str[0] = 'X' #=> FrozenError (can't modify frozen String)
But you can assign new string or change its reference. Once the reference change then it is not freeze (or constant) object.
str = "this is string"
str.freeze
str.frozen? #=> true
str = "this is new string"
str.frozen? #=> false
arr = ['a', 'b', 'c']
arr.freeze
arr << 'd' #=> FrozenError (can't modify frozen Array)
arr[0] = 'd' #=> FrozenError (can't modify frozen Array)
arr[1].replace('e') #=> ["a", "e", "c"]
arr.frozen? #=> true
arr array is frozen means you can’t change the array. But the strings inside the array aren’t frozen. If you do a replace operation on the string “one”, mischievously turning it into “e”, the new contents of the string are revealed when you reexamine the (still frozen!) array.
hash = {a: '1', b: '2'}
hash.freeze
hash[:c] = '3' #=> FrozenError (can't modify frozen Hash)
hash.replace({c: '3'}) #=> FrozenError (can't modify frozen Hash)
hash.merge({c: '3'}) #=> return new hash {:a=>"1", :b=>"2", :c=>"3"}
hash.merge!({c: '4'}) #=> FrozenError (can't modify frozen Hash)
hash.frozen? #=> true
hash = {:a=>"1", :b=>"2", :c=>"3"}
hash.frozen? #=> false
So we can't modify the hash content but we can refer it to new hash (just like array)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With