replace spaces with commas?

Discussion in 'Ruby' started by John Griffiths, Nov 3, 2008.

  1. Been looking at the Acts As Taggable On Steriods plugin, by default it
    makes each word separated by a comma a tag but I really wanted an easier
    way to handle this so each word gets a comma put between it so it
    becomes a tag and the user doesn't have to worry about this.

    so i built this, which seems to work kinda well,

    @s = "fdsdsf, dsfdsfsd fdsfdsfd dfsfds"
    puts @s.gsub(',','').split( / */ ).join(',')

    returns => "fdsdsf,dsfdsfsd,fdsfdsfd,dfsfds"

    what do you think or is there an easier method?
    John Griffiths, Nov 3, 2008
    1. Advertisements

  2. RnJvbTogSm9obiBHcmlmZml0aHMgW21haWx0bzppbmRpZWhlYWRAZ21haWwuY29tXSANCiMgQHMg
    Peña, Botp, Nov 4, 2008
    1. Advertisements

  3. thanks Peña, admittedly regular expressions have never been my strong
    point ;-)

    will give this a go,

    John Griffiths, Nov 4, 2008
  4. John Griffiths

    Henrik Nyh Guest

    Henrik Nyh, Nov 4, 2008
  5. agree, but what i'm after is the same functionality as flickr has when
    tagging photos, each word separated by a space is converted to a tag.

    good stuff ;-)
    John Griffiths, Nov 4, 2008
  6. I would think that you might also want to take care for csv files that
    have string fields.


    "here we go","something here","commas, inside a field",123

    Differentiating internally is extra work. I am not sure if it matters
    in your case as your example may well be greatly pared down, but caveat
    Lloyd Linklater, Nov 4, 2008
  7. This won't retain empty words. If you have to do this you can do

    irb(main):005:0> "fdsdsf, dsfdsfsd fdsfdsfd dfsfds".gsub(/\s*[\s,]\s*/, ','=
    =3D> "fdsdsf,dsfdsfsd,fdsfdsfd,dfsfds"
    irb(main):006:0> "fdsdsf, dsfdsfsd fdsfdsfd dfsfds".gsub(/\s*[\s,]\s*/, ', =
    =3D> "fdsdsf, dsfdsfsd, fdsfdsfd, dfsfds"

    Here's another one

    irb(main):008:0> "fdsdsf, dsfdsfsd fdsfdsfd dfsfds".gsub(/\W+/, ',')
    =3D> "fdsdsf,dsfdsfsd,fdsfdsfd,dfsfds"
    irb(main):009:0> "fdsdsf, dsfdsfsd fdsfdsfd dfsfds".gsub(/\W+/, ', ')
    =3D> "fdsdsf, dsfdsfsd, fdsfdsfd, dfsfds"



    remember.guy do |as, often| as.you_can - without end
    Robert Klemme, Nov 4, 2008
  8. John Griffiths

    Pablo Q. Guest

    Just if you want to play and learn regular expression in ruby, cool stuff

    Pablo Q.
    Pablo Q., Nov 5, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.