Eval, HereDoc and Regular Expressions

I’m having a bit of a problem with Ruby playing nice when it comes to
combining an eval, a combination of lines in a HereDoc, and a regular
expression. Consider this code:

a = 42
puts “yes” if a =~ /\d{2}/ => “yes”
eval(“puts ‘yes’ if a =~ /\d{2}/”) => nil
eval(‘puts “yes” if a =~ /\d{2}/’) => “yes”

OK, so now I realize I should just encapsulate my eval statement inside
a single quote to make my regular expression process correctly. Enter
HereDoc:

a = 42
eval <<-STR
puts “hi” if a =~ /\d{2}/
STR

Doing that code in the console makes it quite obvious that HereDoc
encapsulates things inside double quotes, which would break the regular
expression. My question is whether there is an alternative that will
allow me to include regular expressions into my statement and actually
have them process.

Obviously for such a short snippet of code, I can put everything inside
a single-lined, single-quoted string and be done with it. My problem is
that I’m defining a method within my eval statement that spans 3 or 4
lines, and readability would be absolutely shot if I had to add in a
bunch of semi-colons and escape characters and such.

Thanks,
Adam

On Jan 26, 2007, at 7:35 PM, [email protected] wrote:

a = 42
eval <<-STR
puts “hi” if a =~ /\d{2}/
STR

If you want this to write “hi” to stdout, it should be

a = “42”
eval <<‘STR’
puts “hi” if a =~ /\d{2}/
STR

Notes

  1. the variable a must reference a string not a number.
  2. single-quoting STR tells Ruby to use single-quote rules for the
    HERE doc.
  3. the - after << is not needed since the final STR is not indented.

See the Pickaxe book Part III/Basic Types/Strings for more info.

Regards, Morton

Hi,

At Sat, 27 Jan 2007 09:35:07 +0900,

[email protected] schrieb:

eval <<-STR
puts “hi” if a =~ /\d{2}/
STR

irb(main):001:0> a = “42”
=> “42”
irb(main):002:0> puts “yes” if a =~ /\d{2}/
yes
=> nil
irb(main):003:0> eval(“puts ‘yes’ if a =~ /\d{2}/”)
yes
=> nil
irb(main):004:0> eval(‘puts “yes” if a =~ /\d{2}/’)
yes
=> nil
irb(main):005:0> eval <<-‘STR’
irb(main):006:0’ puts “hi” if a =~ /\d{2}/
irb(main):007:0’ STR
hi

Wolfgang Nádasi-Donner