gerbdla
gerbdla

Reputation: 31

Parsing out string values in Ruby

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

Answers (4)

steenslag
steenslag

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

Andrzej Gis
Andrzej Gis

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

Sergio Tulentsev
Sergio Tulentsev

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

ennuikiller
ennuikiller

Reputation: 46985

string = "car_1_ford"

string.gsub!("_", " ")

Upvotes: 6

Related Questions