So I am pushing some elements on my array like this:
upd_city_list << [ j.children[0].text.strip!.gsub(/\s+\W/, ''), j.children[1].text, j.children[1][:href] ]
The above is in an iterator (hence the use of j).
The issue is that from time to time, the j.children[0].text turns up as nil, and Ruby doesn’t like that.
I could add a bunch of if statements before this assignment, but that seems a bit inelegant to me.
How do I handle nil cases in this situation in an elegant way?
One possible solution is, when there is a nil value, just push the string none onto the array….but what would that look like?
Thanks.
Edit1:
This is the error I am getting:
NoMethodError: private method ‘gsub’ called for nil:NilClass
The real problem is that
strip!returns nil when there are no changes to the string. Yourtextmethod is returning a string, it is yourstrip!method is returning nil. I don’t know why it does this. I dislike it, too.This case of the problem will go away if you just change
strip!tostripIn a more general sense, you might create an object to return the array for you. You don’t want to go changing (what I assume is) Nokogiri, but you can wrap it in something to hide the train wrecks that result.