2

Is it possible to concatenate an integer and a string inside a model? Something like this:

percent = 50
string = (percent + "%")

Trying this I am getting a Type Error:

TypeError (String can't be coerced into Fixnum): app/models/game.rb:124:in `+'

2 Answers 2

4

You can do it by different ways:

string = "#{number}%" # or number.to_s + "%"
=> "50%"

Or by using number_to_percentage Rails helper:

string = number_to_percentage(number)
Sign up to request clarification or add additional context in comments.

3 Comments

number_to_percentage doesn't seem to work: NoMethodError (undefined method `number_to_percentage' for #<Game:0x007fcfb72bd598>):
@Lars, see my answer: only in views, since it is a helper. Or include helpers: include ActionView::Helpers in models.
Ok. I missed this hint. string = "#{number}%" works in my model
1
percent = 50
percentstring = percent.to_s
string = percentstring + "%"

.to_s = to string

2 Comments

According Ruby style guide better use string interpolation instead of concatenation.
he asked for concatenation :P

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.