[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Beginner with a question.

John Joyce

8/3/2007 5:04:00 PM


On Aug 3, 2007, at 11:48 AM, clockwork@sigsys.org wrote:

> So I am new to ruby, and I seem to be stuck on a seemingly simple
> problem. I
> have two variable's, one that is defined in the script, and one
> that is
> grabbed from input. I can add them together just fine, but I have
> not come
> up with a way to put the addition statement inline with strings. For
> instance:
>
> puts favnum.to_i + plus1.to_i
>
> Works producing the expected result. However when I try something
> like this:
>
> puts 'Try ' + favnum + plus1 + ' has the result.'
>
> I get errors. I have tried declaring the variables as integers, and
> tried
> various syntax's on that line, but the solution is escaping me and
> I have
> not found a good way to do this. I would also be willing to do a
> variable to
> define the item I want to add into the line, such as:
>
> finalnum = favnum.to_i + plus1.to_i
>
> But that doesnt produce the desired result either as the following
> doesnt
> work:
>
> puts 'Try '+ finalnum +' instead.'
>
> In both cases I also tried forcing .to_i but that didnt help.
> (though doing
> a "puts finalnum" works.)
>
> So what sort of silly syntactical error am I making ?
>
> (Apologies if this is the wrong place to post this, it seemed like
> my best
> bet.)
>
> ~Clockwork
Very simple actually,
read those error messages!
You're trying to do math and concatenation of strings at the same time.
so you have some options.
One of them is using .to_s on those numbers to turn them into strings.
But if you wan the result of adding or subtracting or what have you,
then you need parentheses around the math part, followed by .to_s

puts 'Try ' + (favnum + plus1).to_s + ' has the result.'