Strange \n in base64 encoded string in Ruby

后端 未结 6 933
野趣味
野趣味 2020-11-29 00:05

The inbuilt Base64 library in Ruby is adding some \'\\n\'s. I\'m unable to find out the reason. For this special example:

irb(main):001:0> require \'rubyg         


        
6条回答
  •  被撕碎了的回忆
    2020-11-29 00:25

    Edit: Since i wrote this answer Base64.strict_encode64() was added, which does not add newlines.


    The docs are somewhat confusing, the b64encode method is supposed to add a newline for every 60th character, and the example for the encode64 method is actually using the b64encode method.

    It seems the pack("m") method for the Array class used by encode64 also adds the newlines. I would consider it a design bug that this is not optional.

    You could either remove the newlines yourself, or if you're using rails, there's ActiveSupport::CoreExtensions::Base64::Encoding with the encode64s method.

提交回复
热议问题