I think it would be easier not to store the encoding but do .force_encoding here directly. That way you can remove the encoding = nil at the top and the result.force_encoding line at the bottom.