In Rails, I have a date saved in an instance variable. I need to grab the beginning of the decade before it. If @date.year= 1968 then I need to return 1960. How would I do that?
In Rails, I have a date saved in an instance variable. I need to
Share
You can do this several ways. As suggested, you can always use integer division which divides the number and truncates the remainder. So
1968/10returns196and if you multiply it by10, it will give you1960. Or simply,I prefer the method of using modular arithmetic. If you do
@date.year % 10it will return the remainder if you divide by10which you can then subtract from the year like so:The reason I prefer the latter is because integer division truncating the remainder may not be some thing that is obvious to everyone looking at your code. However, modular arithmetic works generally the same in all programming languages.
Keep in mind if you’re trying to change the date, you need to use the appropriate method.