[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Using eval() to create a Regexp object from a string

Ivan V.

7/4/2007 3:52:00 PM

Hi,

I'm trying to create a Regexp object by calling eval like this:

def eval_to_regexp(o)
if o.is_a?(Regexp)
o
elsif o.is_a?(String)
o = o[5..o.size] if o[0..4] == 'eval:'
eval("/#{o}/")
else
eval("/#{o.to_s}/")
end
end

e = eval_to_regexp("eval:some_function() + '^'")

Suppose some_function() returns the string '/home/test'

And then I use it to test a match as follows:

'/home/test' =~ e # should return 0
'/home/test/somethingelse' =~ e # should return nil (because of the '^'
above)

I also tried using /#{o}/ directly instead of the eval, but it doesn't
work either :(

Thanks in advance!

- Ivan V.

--
Posted via http://www.ruby-....

5 Answers

Sebastian Hungerecker

7/4/2007 3:58:00 PM

0

Ivan V. wrote:
> I'm trying to create a Regexp object by calling eval like this:

I'm sorry, but why don't you just do regexp=Regexp.new(your_string) ?


--
NP: Anathema - Pressure
Ist so, weil ist so
Bleibt so, weil war so

dblack

7/4/2007 3:58:00 PM

0

Ivan V.

7/4/2007 4:06:00 PM

0

Sebastian Hungerecker wrote:
> Ivan V. wrote:
>> I'm trying to create a Regexp object by calling eval like this:
>
> I'm sorry, but why don't you just do regexp=Regexp.new(your_string) ?

Because I didn't thought about that and I'm a complete newb regarding
Ruby and Regexp (in general), as pointed out by David's correction (the
'^' is for the start of the string, not the end - thanks!).

Thanks a lot :)

- Ivan V.

--
Posted via http://www.ruby-....

James Gray

7/4/2007 4:43:00 PM

0

On Jul 4, 2007, at 10:51 AM, Ivan V. wrote:

> Suppose some_function() returns the string '/home/test'

I see you already have your answer, but another thing you may want to
be aware of is Regexp.escape():

def some_function; '/home/test' end

re = /#{Regexp.escape(some_function)}/ # => /\/home\/test/
re.source # => "/home/test"

James Edward Gray II

Giles Bowkett

7/5/2007 6:06:00 PM

0

> >> I'm trying to create a Regexp object by calling eval like this:
> >
> > I'm sorry, but why don't you just do regexp=Regexp.new(your_string) ?
>
> Because I didn't thought about that and I'm a complete newb regarding
> Ruby and Regexp (in general), as pointed out by David's correction (the
> '^' is for the start of the string, not the end - thanks!).

Be careful about eval()! I definitely enjoy eval() but you need to
have some perspective. It's not for newbs.

--
Giles Bowkett

Blog: http://gilesbowkett.bl...
Portfolio: http://www.gilesg...