0
problem = 7 + 3
puts problem.to_s

I'm new to Ruby. The code above returns 10. How do I get 7 + 3 as the output, without assigning it to problem as a string in the first place? Am I missing something extremely simple?

2
  • "I'm new to Ruby" – well, this is how evaluation and assignment works in virtually any programming language: the result is being assigned. What are you trying to achieve? Commented Aug 5, 2021 at 16:27
  • @Stefan: if I were to guess, a simple "solve this equation" game. Commented Aug 5, 2021 at 20:43

3 Answers 3

1

Am I missing something extremely simple?

Yes, you are. This is impossible. 7 + 3, as an arbitrary expression, is evaluated/"reduced" to 10 when it's assigned to problem. And the original sequence of calculations is lost.

So you either have to start with strings ("7 + 3") and eval them when you need the numeric result (as @zswqa suggested).

Or package them as procs and use something like method_source.

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

Comments

1

just for fun (don't try at home)

class Integer
  def +(other)
    "#{self} + #{other}"
  end
end

problem = 7 + 3
puts problem.to_s # "7 + 3"

2 Comments

No need for that .to_s, though. Also, don't try it at work. :)
This answer is correct, reflects the only way to obtain the desired result and illustrates the folly of doing so. I like.
0

7 is Fixnum (ruby < 2.4) or Integer (ruby >= 2.4)

"7" is String

So you need to define for ruby what you need because + for Integer is addition, + for String is concatenation:

problem = "7" "+" "3"

That is equal to:

problem = "7+3"

4 Comments

That doesn't work for me, unfortunately. As I stated in the question, I want to keep problem in num + operator + num form for use in other parts of my program.
eval(problem) for calculating string. But that is bad practice
Got you. Thanks for helping!
@tNJipNJR Welcome on SO! Do not forget to accept answer that was useful for you.

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.