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?

tNJipNJR
  • 3
  • 1
  • _"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? – Stefan Aug 05 '21 at 16:27
  • @Stefan: if I were to guess, a simple "solve this equation" game. – Sergio Tulentsev Aug 05 '21 at 20:43

3 Answers3

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
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"
Lam Phan
  • 3,405
  • 2
  • 9
  • 20
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"
zswqa
  • 826
  • 5
  • 15
  • 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. – tNJipNJR Aug 05 '21 at 11:57
  • `eval(problem)` for calculating string. But that is [bad practice](https://stackoverflow.com/a/637431/16236820) – zswqa Aug 05 '21 at 12:01
  • Got you. Thanks for helping! – tNJipNJR Aug 05 '21 at 12:25
  • @tNJipNJR Welcome on SO! Do not forget to accept answer that was useful for you. – zswqa Aug 05 '21 at 12:32