Today I’m going to take a break from ‘talking about my day’ and instead try and explain something technical. Today I’m going to talk about structs, a concept in Ruby we haven’t actually learned at Flatiron yet. This article is inspired by the presentation on Speaker Deck by Ken Collins, so thanks Ken for getting me thinking about structs!
I’m going to try and break down structs into three parts. Concept, Code and Uses…
Concept: A struct is a miniture class, created quickly and at its core it is a class that only has basic getter and setter methods.
Code: There are a few ways to create a struct. I think the easiest to do and understand is as follows…
1
|
|
That’s all there is to it, this quickly creates a Struct Class called Location that keeps track of a locations name, lattitude and longitude coordinates. Which brings us to…
Uses: Structs seem like they are best used for set values for things that don’t need to have any class methods. Things like GPS locations seem like a great reason to use a struct instead of another structure. Any time where you know there is a fixed amount of information you need a struct can be a quick and easy way of storing information about those things, I’m going to try and use structs more and see if I can’t find even more useful ways to implement them!