Math program

I am attempting to write a program that asks the user for two different
arguments. The first argument is an equation (ex. x+3). The second
argument is the value of the variable (ex. x=4). I then want the
solution to be printed to the user. Eventually I want to write a program
that will allow the user to input an equation and use eulers method to
approximate the solution for a given step size but I am having trouble
connecting the users input equation to actual variable in the program if
that makes sense.

Please post how you get the user input.
Using ‘gets’ is easy:

[5] pry(main)> a = gets
=> “4\n”
[6] pry(main)> a.to_i
=> 4

And you have your value in ‘a’. However for the equation, you can use

[14] pry(main)> a = “x+3”
=> “x+3”
[15] pry(main)> b = “x=4”
=> “x=4”
[16] pry(main)> eval(b+";"+a)
=> 7

In this case you are losing control over the ‘a’ variable, which means
have to trust the user as any Ruby code can be run with ‘eval’.

Thank you very much. For my purposes right now that is exactly what I
needed. But I am curious as to how the eval function works. Specifically
why you have to put the “;”. I spent a short amount of time browsing the
documentation but couldn’t figure it out.

Phillip L. wrote in post #1052248:

why you have to put the “;”.

With ‘eval’ you can run any Ruby code.

Ruby needs something to separate instructions, it can be either a
newline or a semicolon. ‘newline’ is just better for the human eye.

This is valid:

a = 5
puts a

but this is not (Ruby has no idea what you want, and ‘a’ is not defined

a = 5 puts a
SyntaxError: unexpected tIDENTIFIER, expecting $end
a = 5 puts a
To separate those instructions, I choose semicolon (old Pascal
habits :-):
a = 5; puts a

Of course you can separate them with a newline as well :slight_smile: