Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Ruby Struct Explained

.css-284b2x{margin-right:0.5rem;height:1.25rem;width:1.25rem;fill:currentColor;opacity:0.75;}.css-xsn927{margin-right:0.5rem;height:1.25rem;width:1.25rem;fill:currentColor;opacity:0.75;}4 min readIn simple words, Ruby Struct is a built-in class that provides useful functionalities and shortcuts. You can use it for both logic and tests. I will quickly go through its features, compare with other similar stuff, and show some less-known but still useful information about it.All my notes are based on years of hands-on experience at iRonin.IT - a top software development company, where we provide custom software development and IT staff augmentation services for a wide array of technologies.As you can see, it behaves like a simple Ruby class. The above code is equivalent to:What if we want to define the #full_name name on our Employee class? We can do it with Struct as well:Struct is often used to make code cleaner, format more structured data from a hash, or as a replacement for real-world classes in tests.Temporary data structure - the most popular example is a geocoding response where you want to form Address object with attributes instead of a hash with the geocoded data.Cleaner codeTesting - as long as Struct responds to the same methods as the object used in tests, you can replace it if it does make sense. You can consider using it when testing dependency injection.Avoid inheritance from Struct when you can. I intentionally assigned Struct to constant in the above example instead of doing this:When your class inherits from Struct you may not realize that:Arguments are not required - if one of the passed arguments it's an object then calling a method on it will cause an errorAttributes are always public - it is far from perfect encapsulation unless you desire such behaviorInstances are equal if their attributes are equal - Employee.new == Employee.newAccess the class attributes the way you want:Use the equality operator:Iterate over values or pairs:Dig:Hash is also considered as an alternative to Struct. It is faster to use but has worse performance than its opponent (I will test it a little bit later in this article).OpenStruct is slower but more flexible alternative. Using it you can assign attribute dynamically and it does not require predefined attributes. All you have to do is to pass a hash with attributes:Although it may get annoying when you have to type it multiple times:I used the following code to measure the performance of the above solutions:Results:



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Ruby Struct Explained

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×