Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # first, in a lib file I wrote a quick function for gsubbing multiple
- # items in a hash
- class Object::String
- def gsub_from_hash(somehash = {})
- temp = self
- for part in somehash
- unless part[0].nil? or part[1].nil?
- temp = temp.gsub(part[0], part[1])
- end
- end
- temp
- end
- end
- # say I have a field called some_expression,
- # and after submitting a form, we have:
- # my_object.some_expression = "($A + $B) * $C"
- #Then you can gsub the values for your variables:
- real_formula = my_object.some_expression.gsub_from_hash({'$A' => '6', '$B' => '9', '$C' => '4' })
- # note that I had to pass the numbers as String objects -
- # the gsub_with_hash function would need further tweaking to get it
- # to accept both strings and numbers
- # now real_formula looks like "(6 + 9) * 4"
- # since this is a valid mathmatical operation, you can use eval
- answer = eval real_forumla
- # answer => 60
Add Comment
Please, Sign In to add comment