4

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?

1
  • 2
    The fact that String#to_s is defined is a message from the developer of Ruby that you should go with the second one. Cases like this is the only case where String#to_s would be useful. Commented Apr 30, 2013 at 19:55

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

Go for the second approach without hesitation.

The first one is convoluted and doesn't really add any meaning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.