From: Raul Parolari Date: 2007-11-24T03:23:19+09:00 Subject: Re: New at regexp and Ruby need help on parsing a string. Gabra Kadabra wrote: > Raul Parolari wrote: >> >> str.scan(/ (and|not) (.*?) (?= \band|\bnot|$) /x) do |k, v| >> smoking_table[k.to_sym].push(v.strip) >> end > > I think Raul just convinced me that I really need to start a deep > relationship with regexp. > This is magic in one row, readable in three. > > Thanks. I totally agree with you; this is not a subject that you learn 'just trying' or even reading the forum. Start with calm from the basics with a good book, and soon those funny hieroglyphics will become your friends. By the way, the code above did not deal with 'notorious bad girls' (I mean words beginning with 'not'); I had only checked for an absence of prefix, not of suffix. So, here it is (the '\b' before and after a word makes sure that it is indeed a 'word'): str = "and stuff and nice things not notorious bad girls not greasy boys and girslsandboys" h = { :and => [], :not => [] } str.scan(/ (and|not) (.*?) (?= (\b(and|not)\b)|$) /x) do |k, v| h[k.to_sym].push(v.strip) } end p h # => {:and=>["stuff", "nice things", "girslsandboys"], # :not=>["notorious bad girls", "greasy boys"]} Peter Vanderhaden wrote > Interesting solution. One question, how did you print the output? I'm > a newbie and the output I got when I tried your solution came out .. By default, the puts/print methods for hashes concatenate keys and values; you can use 'p' (or 'puts inspect') to see the hash. If you are in irb, just writing the name of the hash will show it to you. Regards Raul -- Posted via http://www.ruby-forum.com/.