Ruby evaluate without eval?
You must either or eval
it, or parse it; and since you don't want to eval
:
mathstring = '3+3'
i, op, j = mathstring.scan(/(\d+)([+\-*\/])(\d+)/)[0] #=> ["3", "+", "3"]
i.to_i.send op, j.to_i #=> 6
If you want to implement more complex stuff you could use RubyParser
(as @LBg wrote here - you could look at other answers too)
Eval a string without string interpolation
You can do this via regex by ensuring that there are an even number of backslashes before the character you want to escape:
def safe_eval(str)
eval str.gsub( /([^\\](?:\\\\)*)#(?=[{@$])/, '\1\#' )
end
…which says:
- Find a character that is not a backslash
[^\\]
- followed by two backslashes
(?:\\\\)
- repeated zero or more times
*
- repeated zero or more times
- followed by a literal
#
character - and ensure that after that you can see either a
{
,@
, or$
character. - and replace that with
- the non-backslash-maybe-followed-by-even-number-of-backslashes
- and then a backslash and then a
#
Evaluate string as an expression
Take a look at Kernel#eval
[~]$ irb
2.1.2 :001 > eval("2 + 3 + 4")
=> 9
2.1.2 :002 > eval("2 + 3 + 4").class
=> Fixnum
Hope this helps
Convert string to class name without using eval in ruby?
You can try
class Post
end
Object.const_get("Post")
Which returns the Post
class
Ruby eval without round
You could also use mathn
from Ruby's core library:
require 'mathn'
res = eval('44/5') #=> (44/5)
res.to_f #=> 8.8
This library will automatically convert to rationals where appropriate.
When is `eval` in Ruby justified?
The only case I know of (other than "I have this string and I want to execute it") is dynamically dealing with local and global variables. Ruby has methods to get the names of local and global variables, but it lacks methods to get or set their values based on these names. The only way to do AFAIK is with eval
.
Any other use is almost certainly wrong. I'm no guru and can't state categorically that there are no others, but every other use case I've ever seen where somebody said "You need eval for this," I've found a solution that didn't.
Note that I'm talking about string eval here, by the way. Ruby also has instance_eval
, which can take either a string or a block to execute in the context of the receiver. The block form of this method is fast, safe and very useful.
How to convert a statement in a string into a format that can be evaluated (Ruby)
You are looking for eval. Here:
a = "true && false"
eval a
# => false
a = "true && true"
eval a
# => true
eval
will let you "convert a boolean statement stored in a string into a format that can be evaluated". You will need to change your logic accordingly to use it.
How to invoke classes dynamically without using eval?
c = MySpace.const_get(e)
Related Topics
How to Interpolate a Variable in a Ruby Regex
When Should I Use Datetime VS Date, Time Fields in Ruby/Rails
Return True Only If All Values Evaluate to True in Ruby
Openssl::Cipher::Ciphererror When Running Staging Db on Local
How to Get the File Creation Time in Ruby on Windows
Rails Object#Blank? VS. String#Empty? Confusion
Initializing a Hash with Empty Array Unexpected Behaviour
Chromedriver Devtools Port Number Error
Ruby: Wait for All Threads Completed Using Join and Threadswait.All_Waits - What the Difference
Where Does Rails Store Data Created by Saving Activerecord Objects During Tests
When Is the Do Keyword Required in Ruby
Assign to an Array and Replace Emerged Nil Values
How to Recursively Flatten a Yaml File into a JSON Object Where Keys Are Dot Separated Strings