Code to reduce redundancy in ruby