0

I have a ruby string car_1_ford I want the out put to be

car 1 ford

what is the best way in ruby to parse this string?

1
  • 2
    Do you want 'car 1 ford' or ['car', '1', 'ford'] as your result? Commented Dec 23, 2011 at 22:31

4 Answers 4

6
string = "car_1_ford"

string.gsub!("_", " ")
Sign up to request clarification or add additional context in comments.

Comments

2

If you're trying to break that string into 3 pieces, then use this code

s = 'car_1_ford'
s.split('_')

(oh, there's ^ an emoticon :-) )

Result will be this

['car', '1', 'ford']

Comments

1

If you'll ever need some more advanced patterns you can use regular expressions.

Here you have Documentation.

Example:

irb(main):012:0> "a_b----c==d".gsub!(/[-_=]+/, ' ')
=> "a b c d"

Comments

0
"car_1_ford".tr('_', ' ') #=> "car 1 ford"

If you only substitute a character for another character then the #tr method is nice, and it alows for multiple changes in one go:

"car_1_ford#model T".tr('_#', ' :') #=> "car 1 ford:model T"

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.