Reputation: 31
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?
Upvotes: 0
Views: 157
Reputation: 80105
"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"
Upvotes: 0
Reputation: 14316
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"
Upvotes: 1
Reputation: 230561
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']
Upvotes: 2