similarly ugly working ruby and javascript solutions