An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
Last month I learnt - ruby can be weird
I was working on a task that involved parsing data from CSV files and saving it into rails models when I noticed something that didnt look right. On calling to_json
on one of the parsed csv rows, I got;
{ "": null, "name": "John"}
For context, I was parsing the CSV using the headers: true
option, and for some reason, I had an empty header. Since we all know that developers dont make mistakes, it had to be an issue with the data. So, I went hunting.
Another lesson, if youre looking for an issue with data, open it in its raw form. Opening the csv with LibreOffice Calc and choosing the helpful defaults, opened a perfectly good sheet, and surprise, no missing header! Just as I was about to concede that it might be me, I opened the file in my editor(vim) and despite the ugliness, the trailing comma on each line was hard to miss.
With a possible culprit found, it was back to the code to try and get rid of that entry. Q; which ruby type would result in an empty string in json? Now, if you use ruby Id assume theres literally no time youve wanted to use an empty string as a key in your hash, right? But still it gets weirder, on calling to_h
on the row;
{ nil => nil, "name" => "John"}
What?! Yes, nil
is a valid key in a ruby hash. I had to fire up plain irb to make sure it wasnt rails messsing with me. And just to be sure, I confirmed that its also possible to retrieve the value normally with hsh[nil]
P.S If you ever find yourself needing to read json exported from mongo,
BSON::ExtJSON.parse
is your friend.
Original Link: https://dev.to/ngarindungu/last-month-i-learnt-ruby-can-be-weird-1n9a
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To