开发者

converting a string into a mathematical operation (ex: "+2.days")

I need to be able add days or hours to a previously created Item.

The system can add or subtract a set number of hours or days based on attributes stored in the db, :operator (add/subtract), :unit_of_time(hours/days), and :number.

I'd like to be able to do something like:

Date.tod开发者_如何转开发ay+2.days

where "+" is the :operator, "2" is the :number, and "days" is the :unit_of_time but I'm unsure of how to get the interpolated string of attributes to become the actual operator "+2.days". Any ideas?

(I've poured through the ruby documentation, but to no avail. Currently, I'm just manually creating of the possible options (4) in nested if/else blocks... yeah it's gross.)


You could use eval, e.g.:

eval("Date.today+2.days")

...and then simply use string interpolation to put in the variables. Note, however, that you should only do this if you can be very certain that the values in your database are always what you want them to be; under no circumstances should users be able to change them, otherwise you'll have a major security issue which compromises your entire system.

Using more lengthy methods like the if statement you suggested (or a case statement) require you to write more code, but they are much more secure.


All ruby objects have a send method which can be used to run a method by name with parameters. Using send as well as converting strings to ints (.to_i) should suffice.

Date.today.send '+', '1'.to_i.send('months') # This works
Date.today.send operator, number.to_i.send(unit) # Generalized form

Ruby is beautiful!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜