tNJipNJR
tNJipNJR

Reputation: 3

Converting math expression to string in Ruby

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?

Upvotes: 0

Views: 319

Answers (3)

Lam Phan
Lam Phan

Reputation: 3811

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"

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

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.

Upvotes: 1

zswqa
zswqa

Reputation: 914

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"

Upvotes: 0

Related Questions