On Dec 6, 6:38 am, Jano Svitok <jan.svi... / gmail.com> wrote:
> On Dec 6, 2007 12:49 PM, Lee Jarvis <ljjar... / gmail.com> wrote:
>
> Sometimes it's better to cache the /#{var}/ as in this case, new
> regexp object is created on each pass through the cycle.
> That might hurt the performance a bit. So:
>
> > var = "hello"
> + var_re = /#{var}/
> > File.foreach "file.txt" do |line|
>
> -   if /#{var}/ =~ line
> +   if var_re =~ line
>
> >     puts "found it"
> >     break
> >   end
> > end
>
> (This might apply for 1.8 MRI only, other interpreters might be
> different): When the regex literal contains #{}, the object
> is created on each pass through the code. In the other case it's
> created only once.
>
> Jano

You can also use the /o option, which tells Ruby to compile the Regex
only once:

var = "hello"
File.foreach "file.txt" do |line|
  if /#{var}/o =~ line
    puts "found it"
    break
  end
end