Guest User

Untitled

a guest
Feb 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1.  
  2. # first, in a lib file I wrote a quick function for gsubbing multiple
  3. # items in a hash
  4. class Object::String
  5. def gsub_from_hash(somehash = {})
  6. temp = self
  7. for part in somehash
  8. unless part[0].nil? or part[1].nil?
  9. temp = temp.gsub(part[0], part[1])
  10. end
  11. end
  12. temp
  13. end
  14. end
  15.  
  16.  
  17.  
  18. # say I have a field called some_expression,
  19. # and after submitting a form, we have:
  20. # my_object.some_expression = "($A + $B) * $C"
  21.  
  22.  
  23. #Then you can gsub the values for your variables:
  24. real_formula = my_object.some_expression.gsub_from_hash({'$A' => '6', '$B' => '9', '$C' => '4' })
  25. # note that I had to pass the numbers as String objects -
  26. # the gsub_with_hash function would need further tweaking to get it
  27. # to accept both strings and numbers
  28.  
  29. # now real_formula looks like "(6 + 9) * 4"
  30. # since this is a valid mathmatical operation, you can use eval
  31.  
  32. answer = eval real_forumla
  33.  
  34. # answer => 60
Add Comment
Please, Sign In to add comment