another (simple!) eval question!

M

mouse_059

greetings Rubyists,

Still trying to wrap my head around metaprogramming.

def analyze(args)
# stuff
# total is defined up here and is equal to some amount of seconds
elapsed (say 100,000)

day, hour, min = 0, 0, 0
loop do day += 1; total -= 86400; break if total < 0; end; day -= 1;
total += 86400
loop do hour += 1; total -= 3600; break if total < 0; end; hour -=
1; total += 3600
loop do min += 1; total -= 60; break if total < 0; end; min -= 1;
total += 60

puts "your total is #{day} days, #{hour} hours, #{min} mins,
#{total} secs"
end

as you can see, i'd like to refactor that so i just have to
dotime( :day, 86400 )
dotime( :hour, 3600 )
dotime( :min, 60 ) (i can hardcode 'total' in the
function, doesn't matter?)

But no eval I use works, either the eval isn't defined for my class
(assume main:Object) or I get "no method for + (nilpointer). I read
about how you shouldn't use string eval, etc. A simple pointer to
some help would be awesome! Thanks guys.

PS, if a time function does this, don't spoil the metaprogramming for
me? I'd like to learn anyway. :)

-Mike
 
R

Robert Klemme

2007/10/23 said:
greetings Rubyists,

Still trying to wrap my head around metaprogramming.

def analyze(args)
# stuff
# total is defined up here and is equal to some amount of seconds
elapsed (say 100,000)

day, hour, min = 0, 0, 0
loop do day += 1; total -= 86400; break if total < 0; end; day -= 1;
total += 86400
loop do hour += 1; total -= 3600; break if total < 0; end; hour -=
1; total += 3600
loop do min += 1; total -= 60; break if total < 0; end; min -= 1;
total += 60

puts "your total is #{day} days, #{hour} hours, #{min} mins,
#{total} secs"
end

as you can see, i'd like to refactor that so i just have to
dotime( :day, 86400 )
dotime( :hour, 3600 )
dotime( :min, 60 ) (i can hardcode 'total' in the
function, doesn't matter?)

But no eval I use works, either the eval isn't defined for my class
(assume main:Object) or I get "no method for + (nilpointer). I read
about how you shouldn't use string eval, etc. A simple pointer to
some help would be awesome! Thanks guys.

PS, if a time function does this, don't spoil the metaprogramming for
me? I'd like to learn anyway. :)

I have no idea why you think there should be an eval in there.

What I'd do: I'd put sizes into an array and use that together with
modulus calculations to split up seconds into years, months, days etc.

Kind regards

robert
 

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,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top