Forum: Ruby eval, HereDoc and Regular Expressions

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
D689f1592faf0864644346f08bc70f5c?d=identicon&s=25 Adam Traver (atraver)
on 2007-01-27 01:35
(Received via mailing list)
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

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

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.

F3b02532d4cb4855881935c002389213?d=identicon&s=25 Morton Goldberg (Guest)
on 2007-01-27 08:30
(Received via mailing list)
On Jan 26, 2007, at 7:35 PM, wrote:

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

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

a = "42"
eval <<'STR'
   puts "hi" if a =~ /\d{2}/


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
F1d6cc2b735bfd82c8773172da2aeab9?d=identicon&s=25 Nobuyoshi Nakada (Guest)
on 2007-01-27 08:39
(Received via mailing list)

At Sat, 27 Jan 2007 09:35:07 +0900,
A131b672fdbd2a58dce12031ad78b121?d=identicon&s=25 Wolfgang Nádasi-Donner (wonado)
on 2007-01-27 10:51
(Received via mailing list) schrieb:
> eval <<-STR
>   puts "hi" if a =~ /\d{2}/

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

Wolfgang Nádasi-Donner
This topic is locked and can not be replied to.