eval, HereDoc and Regular Expressions

A

atraver

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
 
M

Morton Goldberg

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
 
W

Wolfgang Nádasi-Donner

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top