Change ported from pull request in ruby by https://github.com/locochris