Hi, First see the code :
a = 'foo bar baz 12 34 ret'
b = '2.bar foo tree ream baz foo'
match = Regexp.union(a.split(" "))
b.gsub(match) { |m| p m }
# >> "bar"
# >> "foo"
# >> "baz"
# >> "foo"
What I am looking for is, for every match inside the block I want to
substitute the $` to set to empty string(`""`). so that at the end of
gsub I get at last final string "bar foo baz".
In the example above you have 4 matches, and you want the final string to be "bar foo baz".
Where do the spaces in the final string come from?
Where did the second "foo" go?
But I am getting error as
a = 'foo bar baz 12 34 ret'
b = '2.bar foo tree ream baz foo'
match = Regexp.union(a.split(" "))
b.gsub(match) { |m| $`=""; m }
# ~> -:6: Can't set variable $`
With gsub how can I do that?
I dont understand what you are trying to do. If you want to "ignore" the stuff which currently ends up in $` you need to match it as gsub replaces what was matched. For example:
~ ∙ pry
[1] pry(main)> a = 'foo bar baz 12 34 ret'
=> "foo bar baz 12 34 ret"
[2] pry(main)> token_re = Regexp.union(a.split(" "))
=> /foo|bar|baz|12|34|ret/
[3] pry(main)> b = '2.bar foo tree ream baz foo'
=> "2.bar foo tree ream baz foo"
[4] pry(main)> b.gsub(/.*?(#{token_re})/, '\1')
=> "barfoobazfoo"
might give you a good starting point, I recommend using rubular.com to play with regular expressions and reading Class: Regexp (Ruby 2.1.0) to understand what .*? does.
If you just want a list of tokens matched then I wouldn't use gsub:
[5] pry(main)> b.scan(token_re).join(' ')
=> "bar foo baz foo"
and if you just want unique tokens matched:
[8] pry(main)> b.scan(token_re).uniq.join(' ')
=> "bar foo baz"
Hope this helps,
Mike
···
On Feb 11, 2014, at 12:03 AM, Arup Rakshit <lists@ruby-forum.com> wrote:
--
Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/
The "`Stok' disclaimers" apply.