Reputation: 3755
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?
Upvotes: 4
Views: 92
Reputation: 160301
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.
Upvotes: 4
Reputation: 3825
Go for the second approach without hesitation.
The first one is convoluted and doesn't really add any meaning.
Upvotes: 1
Reputation: 30473
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.
Upvotes: 3