Topic: Combine multiple gsubs

Is it possible to combine multiple gsubs?

having:
sentence = "This is a sentence with multiple words and one line"

Is there a cleaner way to do this?
sentence.gsub('with','').gsub('and', '').gsub.('one','') => "This is a sentence  multiple words   line"

Thank you!

Last edited by jazmin (2011-06-07 13:30:17)

Re: Combine multiple gsubs

Try like that:

sentence = "This is a sentence with multiple words and one line"
r = sentence.gsub(/with|and|one/,'')
puts "result: #{r}"

Re: Combine multiple gsubs

Quick follow-up question.  I've got a list of tags in an array

@product.tags
=> [#<Tag id: 21, name: "Crayon">, #<Tag id: 16, name: "Green">]

I also have a list of categories

@categories
=>[#<Tag id: 16, name: "Green">, #<Tag id: 17, name: "Blue">, #<Tag id: 18, name: "White">]

Normally the tag list would show both the tags and categories, but I'm trying to only show the tags, so I need some way to gsub out the array of categories. i.e.

<%= (text_field :product, 'tag_list', :size => 50).gsub(@categories.map{|x| x.name, "") %>

Any idea how I can accomplish that?

Last edited by viniosity (2011-07-26 01:31:59)

Re: Combine multiple gsubs

Are there 2 separate arrays?  Try simple array subtraction.  Or if it's a single array composed of both Tag and Category objects, you could check the "class" method for only "Tag".

array_of_tags_and_categories = [...]
array_of_only_tags = array_of_tags_and_categories.select{ |item| item.class == "Tag" }

Just a quick solution off the top of my head.

I think the real question is, though, why are you combining tags and categories if you need to display them separately?  I would recommend storing them in separate array variables from the start and not worry about separating them.  But that's because I probably don't understand your use case.

Last edited by daniel_l (2012-02-28 11:11:58)