We can claim to be experts in Ruby, and there are so many things we always want to share with you. For example, let’s check what do you know about Ruby Struct?
In simple words, Ruby Struct is a built-in class which provides useful functionalities and shortcuts. You can use it for both logic and tests. We will quickly go through its features, compare with other similar stuff and show some less-known but still useful information about it.
Struct is often used to make code cleaner, format more structured data from hash or as a replacement for real-world classes in tests.
- Temporary data structure – the most popular example is geocoding response where you want to form
Addressobject with attributes instead of a hash with the geocoded data.
- Cleaner code
- Testing – as long as
Structrespond 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.
Find more examples here.
You can read about e-commerce solutions, Rails security, row sorting library, testing Rails engines and other great RoR projects on GitHub in our monthly trending Ruby on Rails repositories digest!