0

I tried to pass array of string to use puts in ruby print it value with math operator. But get the wrong result. I thingk it need to convert to object to achieve this as follow.

my_string_array     =  ["100*(4+1)"]
my_string = my_string_array.join(' ') # => "100*(4+1)"
my_ruby_valuation = my_string.to_i # => 100 (Wrong)

What I expected is

puts my_ruby_valuation #=> 500
2
  • 4
    Are you trying to execute the code in the string? In that case, use eval, but there are security concerns to look for. Commented Jun 11, 2020 at 6:47
  • Yes, (thank for security issue but it's internal process for this one). It's work Would you move or add your comment in answer Commented Jun 11, 2020 at 13:15

1 Answer 1

1

You should use eval kernel function. https://apidock.com/ruby/Kernel/eval

 my_string_array     =  ["100*(4+1)"]
 eval(my_string_array[0])

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.