I have a function that manipulates a string; however, sometimes my input isn't already a string. For example it could be a path object. I need to convert it to a string because I want to call methods like .gsub
.
My question seems a bit simple, but I'm debating on the best approach for converting the object to a string.
I currently have two options:
str = str.to_s unless str.is_a? String
or
str = str.to_s
The second method is much simpler, but the first method actually describes what's going on. I'm wondering which of these two methods is better to use or if there's a better approach I haven't thought of?
I would prefer the second one.
I'd prefer the parameter/variable wasn't named str
if it isn't a string.
Naming it str
implies string, but then the code looks silly, and is harder to reason about.
I prefer second one. It is shorter, simplier and also describes what you want (any programmer will understand what will heppen). Also there is no notable difference in perfomance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With