Avoiding eval

A

Andrew Wagner

[Note: parts of this message were removed to make it a legal post.]

Hey all,
If I have a string like "Math", I know I can use const_get to turn it into
an instance of Class. Awesome.

But what if I have something like "Math::pI". Am I stuck using eval to
resolve that?
 
R

Robert Klemme

If I have a string like "Math", I know I can use const_get to turn it into
an instance of Class. Awesome.

But what if I have something like "Math::pI". Am I stuck using eval to
resolve that?

One typical idiom looks like this:

a_class = str.split('::').inject(Object) {|cl,n| cl.const_get n}

Cheers

robert
 
A

Andrew Wagner

[Note: parts of this message were removed to make it a legal post.]

Well, sure. That's a good point. But now you're taking 3 times as long as
eval, instead of 1/5 the time, according to my tests.
 
R

Robert Klemme

Please do not top post.

Well, sure. That's a good point. But now you're taking 3 times as long as
eval, instead of 1/5 the time, according to my tests.

Is it a performance issue? If not, why bother now? The version with
eval is much less secure plus eval might not work under all
circumstances with your string (see $SAFE).

Cheers

robert
 
A

Andrew Wagner

[Note: parts of this message were removed to make it a legal post.]

Err, I think I wasn't very clear in my last email, so I'll say it in a
benchmark this time.

require 'benchmark'

Benchmark.bm do |b|


b.report "using eval" do
1_000_000.times { eval "Math" }
end

b.report "using const_get" do
1_000_000.times { Kernel.const_get "Math" }

end

b.report "using eval on Math::pI" do
1_000_000.times { eval "Math::pi" }

end

b.report "using const_get injection on Math::pI" do
1_000_000.times { "Math::pI".split("::").inject(Object) { |cl,n|
cl.const_get n } }

end

end

using eval 6.5
using const_get 1.297
using eval on Math::pi 6.875
using const_get injection on Math::pI 18.65

Without the performance benefit, it seems like there's not much benefit in
avoiding eval :(.
 
J

Josh Cheek

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

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top