5 Ruby tips you probably don't know
5 Ruby Tips You Probably Don’t Know - RubyCademy - Medium
In this article we’re going to explore the following topics:assigning the rest of an Array to a variablearray destructuring in block argumentsHash#default_proc as default valueHEREDOC and method chainingunary operators for non-numeric objectsAssigning the rest of an Array to a variableWhen destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest patternArray destructuring in block argumentsIt’s possible to use Array Destructuring in ruby blocksproduceskey1: value1key2: value2key3: value3key4: value4Here, each sub-array is destructured and the first and second entry values are assigned to the key and value block arguments.Hash#default_proc as default valueA Hash.new can take a block that will be used to set the default value of a keyBut what if we want to propagate this default value through all the entries and subentries of a hash?It’s possible to propagate the default block passed as an argument of the Hash.new method to all the sub-entries of the freshly returned hash.To do so we can use Hash#default_proc that contains the block passed as an argument of the Hash.new methodHere, a new hash that takes a block as an argument — which is used to define the default value of a new entry — is assigned to the layers variable.When layers[:layer_1] is called without an explicit assignment, then the block passed as an argument of the layers hash is executed.This block is executed as followingIn effect, the default_proc executes the block passed as an argument of the layers hash.It’s the same for the layers[:layer_1][:layer_2].And then the layers[:layer_1][:layer_2][:layer_3] contains an assigned value. So the default_proc method is not called.The default_proc method of the layers hash is propagated as the default value of any new entries and sub-entries of this hash.Inception…HEREDOC and method chainingAs an HEREDOC is a multi-line string syntactic sugar, then it’s possible to chain methods on it.In this example, we remove the trailing spaces and \n for a SQL queryNote that the squish method is defined within the Rails framework.Unary operators for non-numeric objectsIt’s possible to implement unary operators to an object by defining the -@ and +@ methods within the class declarationproducesfalsetrueRuby MasteryWe’re currently finalizing our first online course: Ruby Mastery.Join the list for an exclusive release alert! 🔔🔗 Ruby Mastery by RubyCademyAlso, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.💚