Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if an object is a string

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?

like image 557
Josh Wilson Avatar asked Feb 16 '23 16:02

Josh Wilson


2 Answers

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.

like image 161
Dave Newton Avatar answered Feb 28 '23 05:02

Dave Newton


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.

like image 25
Danil Speransky Avatar answered Feb 28 '23 05:02

Danil Speransky