On Monday 30 April 2001 20:18, Yukihiro Matsumoto wrote:
> Hi,
>
> In message "[ruby-talk:14448] How to do it the Ruby-way 2"
>
>     on 01/05/01, Stefan Matthias Aust <sma / 3plus4.de> writes:
> |I really like the way I can embed ruby code in strings using #{}.
> |This code works as expected:
> |
> | def a(name)
> |   print "<#{a.capitalize}>"
> | end
>
> I don't get the point.  "<#{name.capitalize}>"?
>
> |but what if the pattern string isn't a constant but also provided with
> |that method, let's say:
> |
> | def a(pat, name)
> |   print pat
> | end
>
> Do you want to embed the value in pat string?  How about using format
> method?
>
>   def a(pat, name)
>     print format(pat, name.capitalize)
>   end
>   a("<%s>", "foobar")
>
> | def a(pat, name)
> |  eval "print \"#{pat}\""
> | end
> |
> |But, I think, it's really ugly.  I'd like to use a pattern string read
> |in from an external file (from the trusted source) and then emit it
> |using all bindings currently available in that method.  How can this
> |be achieved?
>
> If the above is what you really want, "eval" is what you need.  I
> recommend you the format solution though.
>

There is also Regexp. Following may get you started towards what you want:

[wyzzrd@starcrusher /wyzzrd]$ ruby -e 'r = Regexp.new ("^(.*)\s(.*)$"); 
r.match ("Hello World"); puts $1; puts r.source'
Hello
^(.*) (.*)$
[wyzzrd@starcrusher /wyzzrd]$ 

An there is also:

[wyzzrd@starcrusher /wyzzrd]$ ruby -e 'x = []; 
File.open("test.re").readlines.each do |line| x << Regexp.new(line); end; 
x.each do |r| puts r.source; end'
^(.*)\s(.*)$
^[Hh](.*)\s(.*)orld$
^[Hh]?(.*)\sWorld$

[wyzzrd@starcrusher /wyzzrd]$ 

which comes from a file.

Anyway, play around with it; it may be what you want.

Hope this helps :-)

Regards,

Kent Starr
elderburn / mindspring.com