Problem using #{...} in eval

R

Richard

Below is my "show" method followed by some tests. I envision using
something like this to produce a tutorial for myself. Examples 1 & 2
demonstrate that "show" accepts a source code string and then displays
the source code followed by the result one would obtain by executing
that code in a stand-alone environment.

But Example #3 does not transmit elements of string (identified by a
pattern) to a succeeding string. However, Example #4 demonstrates that
code in #3 (even with an abstraction for the number of digits) works
fine outside of "eval".

Is this problem the result of a limitation in eval, or is the a way to
code it so it works?

====== results =========
ruby Test1.rb
a=2; b=3; a*b
=> 6


hrs=24;
mins=60;
"mins/day = " + (hrs*mins).to_s
=> mins/day = 1440

require 'bigdecimal'
require 'bigdecimal/math'
include BigMath
BigMath::pI(6).to_s =~ /.(.)(.)(.{5})/
"result = " + ""
=> result =

Pi = 3.14159 (to 6 significant digits)
Exit code: 0

======= code =========
def show(stmt)
puts stmt
puts "=> " + eval(stmt).to_s
puts
end

#1: Works great
show("a=2; b=3; a*b")

#2: Works great, too
show(%Q@
hrs=24;
mins=60;
"mins/day = " + (hrs*mins).to_s
@)

#3: Can't find the elements of the match
show(%Q@require 'bigdecimal'
require 'bigdecimal/math'
include BigMath
BigMath::pI(6).to_s =~ /.(.)(.)(.{5})/
"result = " + "#{$2}#{$1}#{$3}"
@)

#4: But this can find them just fine:
require 'bigdecimal'
require 'bigdecimal/math'
include BigMath
n=6
BigMath::pI(n).to_s =~ /.(.)(.)(.{#{n-1}})/
puts "Pi = #{$2}#{$1}#{$3} (to #{n} significant digits)"
 
J

John W. Long

Richard said:
#3: Can't find the elements of the match
show(%Q@require 'bigdecimal'
require 'bigdecimal/math'
include BigMath
BigMath::pI(6).to_s =~ /.(.)(.)(.{5})/
"result = " + "#{$2}#{$1}#{$3}"
@)


You need to escape the # signs with a slash:

show(%Q@require 'bigdecimal'
require 'bigdecimal/math'
include BigMath
BigMath::pI(6).to_s =~ /.(.)(.)(.{5})/
"result = " + "\#{$2}\#{$1}\#{$3}"
@)
 
R

Richard

Hi John,

Thank you very much. Now that you point out I need to escape those
"pound signs", it makes sense.

That enabled me to do what I *really* wanted to do: set a variable "n"
to the number of significant digits wanted. The result (which doesn't
address rounding, which I'll add):

show(%Q@require 'bigdecimal'
require 'bigdecimal/math'
include BigMath
n=20
BigMath::pI(n).to_s =~ /.(.)(.)(.{\#{n-1}})/
"result = " + "\#{$2}\#{$1}\#{$3}"
@)

Again, many thanks for your expert insight.

Best wishes,
Richard
 

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,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top