Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have an API controller that receives information about a media file's path and id3 tags, and saves them to an Active Record instance, using PostgreSQL/Rails.
Sometimes however the user sends strings such as:
"genre"=>"Hip-Hop\u0000Hip-Hop/Rap"
and Rails/Postgres aren't exactly happy about that when trying to persist on save
:
An ArgumentError occurred in internals#receive:
string contains null byte
activerecord (3.2.21) lib/active_record/connection_adapters/postgresql_adapter.rb:1172:in `send_query_prepared'
How can I clean this string in Ruby to completely remove null bytes?
–
–
–
The gsub
method on String
is probably suitable. You can just do string.gsub("\u0000", '')
to get rid of them.
http://ruby-doc.org/core-2.1.1/String.html#method-i-gsub
–
The String.delete
method is a better choice because it performs better than both String.tr
and String.gsub
; as long as you are replacing with an empty string there is never a reason to choose tr or gsub over delete.
"Hip-Hop\u0000Hip-Hop/Rap".delete("\u0000")
# => "Hip-HopHip-Hop/Rap"
However, in this case, the string does not make sense with the null character simply deleted, and should probably be replaced with a space (or other delimiting character), so we are back to gsub. But please note that "\u0000" is not visible, so generally a deletion makes sense.
"Hip-Hop\u0000Hip-Hop/Rap".tr("\u0000", " ")
# => "Hip-Hop Hip-Hop/Rap"
AppSignal has a nice blog post detailing and profiling various string replacement methods.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.