# Replacing a formula from a string

**URL:** <https://www.ruby-forum.com/t/replacing-a-formula-from-a-string/75253>\
**Category:** Ruby\
**Created:** [November 8, 2006, 3:01pm UTC](https://www.ruby-forum.com/t/replacing-a-formula-from-a-string/75253 "2006-11-08T15:01:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Josselin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9de0a6/32.png) [@Josselin](https://www.ruby-forum.com/u/Josselin)\
**Post date:** [November 8, 2006, 3:01pm UTC](https://www.ruby-forum.com/t/replacing-a-formula-from-a-string/75253/1 "2006-11-08T15:01:13Z")

</div>

I have a long formula expressed as a string

formula\_1 = “6366.00 \* Math.acos(Math.cos(self.latitude) \*  
Math.cos(latitude) \* Math.cos(longitude -self.longitude) +  
(Math.sin(self.latitude) \* Math.sin(LatitudeRad)) )”

I need to use it in the preparation of some SQL query conditions like :

condition += (c(:villes){ 6366.00 \* Math.acos(Math.cos(self.latitude) \*  
Math.cos(latitude) \* Math.cos(longitude -self.longitude) +  
(Math.sin(self.latitude) \* Math.sin(LatitudeRad)) ) \< distance } )

How could I write it only once ‘formula\_1’ and reuse it like :  
condition += (c(:villes){ formula\_1 \< distance }) # this is wrong as  
formula\_1 is a string …

thansk for your suggestions

joss

---

<div class="post-metadata">

**Author:** ![Josselin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9de0a6/32.png) [@Josselin](https://www.ruby-forum.com/u/Josselin)\
**Post date:** [November 9, 2006, 8:35am UTC](https://www.ruby-forum.com/t/replacing-a-formula-from-a-string/75253/2 "2006-11-09T08:35:47Z")

</div>

Josselin wrote:

> (Math.sin(self.latitude) \* Math.sin(LatitudeRad)) ) \< distance } )
> 
> How could I write it only once ‘formula\_1’ and reuse it like :  
> condition += (c(:villes){ formula\_1 \< distance }) # this is wrong as  
> formula\_1 is a string …

The simplest way to solve this problem is to convert your equation into  
a  
function. Why are you not doing this? Does the equation change  
regularly?

If there are as many equations as database records, then of course you  
want  
to think up a way to interpret the equations as you encounter them. But  
if  
there is one equation and many sets of variables to apply to it, then  
rewrite the text form of your equation as a function. Then read the  
database records, convert the values to numerics, and submit them to the  
function.

Put simply, it’s called “computer programming”.

From this:

> formula\_1 = “6366.00 \* Math.acos(Math.cos(self.latitude) \*  
> Math.cos(latitude) \* Math.cos(longitude -self.longitude) +  
> (Math.sin(self.latitude) \* Math.sin(LatitudeRad)) )”

to this (not tested):

function formula\_1(latitude,longitude,latitude\_rad)  
return 6366.0 \* math.acos(@latitude) \* Math.cos(latitude) \*  
Math.cos(longitude - @longitude) + (Math.sin(@latitude) \*  
Math.sin(latitude\_rad)))  
end
